【问题标题】:Use RXJS and AsyncPipe instead of Observable.subscribe使用 RXJS 和 AsyncPipe 而不是 Observable.subscribe
【发布时间】:2019-06-09 07:59:30
【问题描述】:

在我的 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 仅支持绑定到 Iterables,例如数组”

我当前有效的代码(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());
  })
 })        
});

我只使用没有 AsyncPipe 的纯 *ngFor,即 *ngFor="let s of shortlisted"

我想使用mergeMap 或类似的RXJS 运算符将结果分配给this.shortlisted。目前我无法找到可行的解决方案

请帮忙!

【问题讨论】:

    标签: angular firebase rxjs angularfire2


    【解决方案1】:

    这个应该可以的。

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

    它首先获取感兴趣的初创公司列表,然后为每个初创公司获取该初创公司的文档,并使用combineLatest 连接它们。

    【讨论】:

    • 请注意,您也可以使用combineLatest 作为运算符(然后删除switchMap),但您将获得有趣的初创公司列表作为数组的第一项
    • 嗯...我刚刚将.get() 更改为.valueChanges() 并开始工作。您的回答对我来说是一大进步,因为我花了很多时间尝试使用不同的 RXJS 选项。非常感谢!我需要阅读combineLatest...
    • combineLatest 就像它所说的那样,它结合了给它的每个 observable 的最新值。类似于forkJoin,只不过@9​​87654330@结合了关闭的observables的最后一个值(比如http调用)
    猜你喜欢
    • 1970-01-01
    • 2017-12-13
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2019-12-16
    • 2016-10-25
    相关资源
    最近更新 更多