使用 RXJS 和 AsyncPipe 代替 Observable.subscribe
Use RXJS and AsyncPipe instead of Observable.subscribe
在我的 firebase (angularfire2) 应用程序中,我希望 return 为每个集合元素创建文档。为此,我使用 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 显示下一个错误 "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays"
我当前有效的代码(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
。目前我无法为此找到有效的解决方案
请帮忙!
这个应该可以。
this.shortlisted$ = this.db.collection('interestingStartups').valueChanges().pipe(
switchMap(el => combineLatest(
el.map(is => this.db.doc('startups/' + is.startupUid).get())
))
);
它首先获取感兴趣的初创公司列表,然后针对每个初创公司获取该初创公司的文档,并使用 combineLatest
将它们连接起来。
在我的 firebase (angularfire2) 应用程序中,我希望 return 为每个集合元素创建文档。为此,我使用 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 显示下一个错误 "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays"
我当前有效的代码(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
。目前我无法为此找到有效的解决方案
请帮忙!
这个应该可以。
this.shortlisted$ = this.db.collection('interestingStartups').valueChanges().pipe(
switchMap(el => combineLatest(
el.map(is => this.db.doc('startups/' + is.startupUid).get())
))
);
它首先获取感兴趣的初创公司列表,然后针对每个初创公司获取该初创公司的文档,并使用 combineLatest
将它们连接起来。