使用RXJS和AsyncPipe而不是Observable.subscribe

时间:2019-01-15 10:05:16

标签: angular firebase rxjs angularfire2

在我的firebase(angularfire2)应用中,我希望为集合的每个元素返回文档。为此,我使用Observables + .subscribe()。但是我想使用RXJS和AsyncPipe获得替代方案。

我尝试使用下一个RXJS链:

this.shortlisted$ = this.db.collection(`interestingStartups`).valueChanges().pipe(mergeMap(actions => actions.map(el => {
 return this.db.doc(`startups/${(<any>el).startupUid}`).valueChanges().pipe(mergeMap(el => of([el])));
})));

并在HTML模板中使用*ngFor="let s of shortlisted$ | async"。但这行不通。 Angular显示下一个错误“找不到类型为'object'的其他支持对象'[object Object]'。NgFor仅支持绑定到Iterable,例如数组”

我目前有效的代码(Observables + .subscribe):

this.db.collection('interestingStartups').valueChanges().subscribe((el:any) => {
 el.forEach(is => {
  this.db.doc('startups/' + is.startupUid).get().subscribe(s => {
   this.shortlisted.push(s.data());
  })
 })        
});

我只使用纯*ngFor,而不使用AsyncPipe,即*ngFor="let s of shortlisted"

我想使用this.shortlisted之类的RXJS运算符将结果分配到mergeMap中。目前,我无法为此找到有效的解决方案

请帮助!

1 个答案:

答案 0 :(得分:3)

这应该有效。

this.shortlisted$ = this.db.collection('interestingStartups').valueChanges().pipe(
  switchMap(el => combineLatest(
    el.map(is => this.db.doc('startups/' + is.startupUid).get())
  ))
);

首先获取感兴趣的初创企业列表,然后为每个初创企业获取初创企业的文档,然后使用combineLatest对其进行串联。