角度材料芯片和angularfire2 Firebase

时间:2018-06-13 21:53:43

标签: javascript angular firebase firebase-realtime-database angularfire2

将Firebase数据绑定到Angular Material芯片的最佳方法是什么?

到目前为止我的尝试:

1)从firebase加载数据:

this.locationsRef = this.db.list(`/locations`);
this.locations = this.locationsRef.snapshotChanges().pipe(
  map(changes => changes.map(c => ({ key: c.payload.key, ...c.payload.val() })))
);

2)然后在数据存在之前阻止组件加载:

<mat-form-field class="demo-chip-list" *ngIf="locations | async as fruits">

然而,这种方法不适用于异步数据和过滤。我怎样才能以更好的方式做到这一点?

https://stackblitz.com/edit/angular-rbot4z?file=app%2Fchips-autocomplete-example.ts

您似乎可以使用以下方式执行此操作:

resultsCtrl: FormControl;
filteredResults: Observable<any[]>;

然后:

this.resultsCtrl = new FormControl();
this.resultsCtrl.valueChanges
  .debounceTime(400)
  .subscribe(name => {
    if (name) {
      this.filteredResults = this.filterResults(name);
    }
  });

然后使用这样的东西:

filterResults(name: string) {
  return Observable.create(obs => {
    this.locationRef.snapshotChanges().subscribe(location => {
      if (!location) {
        obs.error(status);
      } else {
        obs.next(location);
        obs.complete();
      }
    });
  });
}

并将html更新为异步:

<mat-autocomplete #resultsAutoComplete="matAutocomplete">
  <mat-option *ngFor="let result of filteredResults | async"
    [value]="result.name">
    <span>{{ result.name }}</span>
  </mat-option>
</mat-autocomplete>

0 个答案:

没有答案