Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何对多个观测值进行排序_Angular - Fatal编程技术网

Angular 如何对多个观测值进行排序

Angular 如何对多个观测值进行排序,angular,Angular,我对Angular2和前端开发一般来说都是新手,所以如果我没有找到明显的答案,我深表歉意 我正在开发Angular2应用程序。我不确定在我正在开发的组件中完成任务的最佳方式 ngOnInit() { console.log("init component"); console.log(this.activatedRoute); this.paramSub = this.activatedRoute.params.switchMap( (params: P

我对Angular2和前端开发一般来说都是新手,所以如果我没有找到明显的答案,我深表歉意

我正在开发Angular2应用程序。我不确定在我正在开发的组件中完成任务的最佳方式

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生命周期钩子期间,我做了两件事,获取并使用服务的route参数,以及从第二个服务获取组织列表。所有这些都很好

我标记为psuedo代码的部分是我想要添加的功能。我想获取前两个服务调用的结果并执行一些业务逻辑


我知道我不能直接使用this.personDetails和this.orgs,因为它们是未定义的(直到异步调用得到解决)。所以我想我需要把它们包装成一个可观察的对象,这样每次它们被更新时我都可以执行一些逻辑。但我不确定该怎么做。任何指向正确方向的指针都将不胜感激。

您可以使用
cobmineLatest()
运算符。为了可读性,我对代码进行了一些重构:

personDetails$=this.activatedRoute.params
.map((params:params)=>params['personId'])
.switchMap(id=>this.personSearchService.getPerson(id))
orgs$=this.personSearchService.getPersonFedOrgs(0)
可观察。组合测试(个人详细信息$,组织$)
.订阅(([详细信息,组织])=>{
控制台日志(详细信息、组织);
})
不要忘记导入操作员:

import 'rxjs/add/observable/combineLatest';

CombineTest执行此任务,但如果其中一个流已发出任何值,它将发出一个值,因此您无法确保在两个流都实际发出值时收到通知

为此,您需要将其压缩为:d

    this.paramSub = this.activatedRoute.params.switchMap(
        (params: Params) => this.personSearchService.getPerson(params['personId']));

    this.orgSub = this.personSearchService.getPersonFedOrgs(0)


Observable.zip(this.paramSub, this.orgSub)
  .subscribe(result) => {
    console.log(result);
  })

谢谢我会试试看。我发现zip:[link]的描述似乎无法编辑我的评论,所以这里是我想要键入的完整评论。我发现zip:[link]的这种描述似乎是CombineTest会等到两个观察者都发出一个值,然后在其中一个发生变化时发出另一个值。其中as zip仅在两个观察者都更改后发出新值。这是正确的评估吗?