如何将选定的角度下拉值绑定到标量值的Observable?

use*_*866 9 observable firebase angularfire2 angular rxjs6

我有一个角度材质选择组件,我想将下拉列表的选定值绑定到来自firebase的Observable of scalar.我想这样做而不需要解开组件中的observable.它看起来我无法使用异步管道绑定值.下面的代码抛出一个异常,因为mat-select的值不能绑定到"uiStateSvc.currentClient $ | async".

<mat-form-field *ngIf="(store.authorizedClients$ | async)?.length > 0">
  <mat-select [(value)]="uiStateSvc.currentClient$ | async" [compareWith]="compareFn">
    <mat-option *ngFor="let client of store.authorizedClients$ | async" [value]="client"
    (onSelectionChange)="changeCurrentClient($event, client)">
      {{ client.name}}
    </mat-option>
  </mat-select>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

我从firebase中提取下拉列表的当前选定值,如下所示:

this.selectedClient$ = this.authSvc.currentUser$.pipe(
      switchMap((x: firebase.User) => {
        if (x != null) {
          return this.afs.doc(`uistate/${x.uid}`).valueChanges().map((y: any) => y.selectedclient);
        } else {
          return Observable.of(null);
        }
      })
    );
Run Code Online (Sandbox Code Playgroud)

Gab*_*ero 5

您正在使用双重绑定,您不能使用管道async来做到这一点,它仅适用于组件中的变量,下面的代码应该可以工作,注意我将 [(value)] 更改为 [value],因此它将从 observable 中读取| async选择的默认值,并存储我在 mat-option 中看到的更改(onSelectionChange)="changeCurrentClient($event, client),这应该足够了

<mat-form-field *ngIf="(store.authorizedClients$ | async)?.length > 0">
  <mat-select
    [value]="uiStateSvc.currentClient$ | async"
    [compareWith]="compareFn"
  >
    <mat-option
      *ngFor="let client of store.authorizedClients$ | async"
      [value]="client"
      (onSelectionChange)="changeCurrentClient($event, client)"
    >
      {{client.name}}
    </mat-option>
  </mat-select>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你