用rxjs进行角度显示以显示第一个可观察物的结果并在其他可观察物完成后合并数据的最佳方法是什么?
例:
@Component({
selector: 'app-component',
template: `
<div *ngFor="let group of groups$ | async">
<div *ngFor="let thisItem of group.theseItems">
...
</div>
<div *ngFor="let thatItem of group.thoseItems">
...
</div>
</div>
`
})
export class AppComponent implements OnInit {
...
ngOnInit() {
this.groups$ = this.http.get<IThisItem[]>('api/theseItems').pipe(
map(theseItems => {
return theseItems.groupBy('groupCode');
})
);
// combine these results? This operation can take 5 seconds
this.groups$$ = this.http.get<IThatItem[]>('api/thoseItems').pipe(
map(thoseItems => {
return thoseItems.groupBy('groupCode');
})
);
}
}
我了解可以通过同时订阅和合并结果来完成。但是是否可以为此使用管道运算符并使用async
管道?
我认为您可以使用combineLatest
rxjs运算符。这可能意味着您也需要稍微更改模板中的处理方式。
我无法使用您的示例,因为我不知道您的get函数,但基本上适用相同的原理。
在此处查看stackblitz的示例:
export class AppComponent {
private firstObservable = of([{name: 'name1'}]).pipe(startWith([]));
private secondObservable = of([{name: 'name2'}]).pipe(startWith([]));
combined = combineLatest(this.firstObservable, this.secondObservable).pipe(
map(([firstResult, secondResult]) => {
return [].concat(firstResult).concat(secondResult)
})
);
}
HTML输出:
<span *ngFor="let item of combined | async">{{item.name}}<span>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句