如何对多个可观察物进行排序 [英] How to sequence multiple observables
问题描述
我一般都不是Angular2和前端开发人员,所以如果我没有找到明显的答案,我深表歉意.
I'm new to Angular2 and front-end development in general, so my apologies if I'm missing the obvious answer.
我正在使用Angular2应用.我不确定要在正在处理的组件中完成任务的最佳方法.
I'm working on an Angular2 app. I'm not sure about the best way to accomplish a task in a component I'm working on.
ngOnInit() {
console.log("init component");
console.log(this.activatedRoute);
this.paramSub = this.activatedRoute.params.switchMap(
(params: Params) => this.personSearchService.getPerson(params['personId']))
.subscribe(result => this.personDetails = result);
this.orgSub = this.personSearchService.getPersonFedOrgs(0).subscribe(
results => this.orgs = results,
error => console.log(error)
);
//pseudo-code
watch this.orgs and this.personDetails
if change
do logic
}
在OnInit生命周期钩子过程中,我做了两件事,我在服务中获取并使用了路由参数,还从第二个服务中获取了组织列表.所有这些都工作正常.
During the OnInit lifecyle hook, I do two things, I get and use a route parameter with a service and I also get a list of organizations from a second service. All of that's working fine.
我标记为伪代码的部分是我要添加的功能.我想获取前两个服务调用的结果并执行一些业务逻辑.
The section I've labeled as psuedo-code is functionality I want to add. I want to take the results of the first two service calls and execute some business logic.
我知道我不能直接使用this.personDetails和this.orgs,因为它们将是未定义的(直到解决了异步调用).因此,我认为我需要将它们包装在Observable中,以便每次更新它们时都可以执行一些逻辑.但是我不确定如何做到这一点.任何朝着正确方向的指针将不胜感激.
I know that I can't directly use this.personDetails and this.orgs because they'll be undefined (until the async calls are resolved). So I think I need to wrap them in an Observable so that I can execute some logic each time they're updated. But I'm not exactly sure how to do that. Any pointers in the right direction would be greatly appreciated.
推荐答案
您可以使用 cobmineLatest()
运算符.为了便于阅读,我对代码进行了一些重构:
You can use cobmineLatest()
operator. I refactored the code a bit for readability:
personDetails$ = this.activatedRoute.params
.map((params: Params) => params['personId'])
.switchMap(id => this.personSearchService.getPerson(id))
orgs$ = this.personSearchService.getPersonFedOrgs(0)
Observable.combineLatest(personDetails$, orgs$)
.subscribe(([details, orgs]) => {
console.log(details, orgs);
})
别忘了导入运算符:
import 'rxjs/add/observable/combineLatest';
这篇关于如何对多个可观察物进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!