如何在Angular 2中将多个Observable组合在一起

前端之家收集整理的这篇文章主要介绍了如何在Angular 2中将多个Observable组合在一起前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我刚刚开始使用Angular 2进行编程,并开始学习subscribe,Subject和BehaviorSubject.目前,我有多个订阅获取存储在我的服务中并发送到组件的值.我的应用程序工作,但我知道这是非常低效的.它在我的组件中失控了:

this.threatService.minLimitChange$.subscribe( min => { this.min = min; this.getSession();});
this.threatService.maxLimitChange$.subscribe( max => { this.max = max; this.getSession();});

(和其他5个获得单个值并且每次调用函数getSession()一样)

在我的threat.service中:

private minLimitChangeSource = new BehaviorSubject<number>(this.min);
private maxLimitChangeSource = new BehaviorSubject<number>(this.max);
minLimitChange$= this.minLimitChangeSource.asObservable();
maxLimitChange$= this.maxLimitChangeSource.asObservable();

所以我试过了:

this.threatService.minLimitChange$.concat(this.threatService.maxLimitChange$).subscribe( res => console.log(res));

我的目的只是为了测试什么是res,因为我不知道如何访问这两个值…但我在控制台中得到了这个. ; /

TypeError: this.threatService.minLimitChange$.merge is not a function. (In 'this.threatService.minLimitChange$.concat(this.threatService.maxLimitChange$)','this.threatService.minLimitChange$.concat' is undefined)

最后,我想从我的服务中获取getSession()所需的所有值并运行该函数一次.我非常感谢有关如何使用concat,merge或forkJoin来组合我的订阅的任何帮助或解释.谢谢!

解决方法

您可以使用Observable.combineLatest将2个可观察流合并为一个:

combineObs = obs1.combineLatest(obs2,(val1,val2) => { 
    return {val1: val1,val2: val2};
  });

工作人员:http://plnkr.co/edit/mmCzEmdKexpaWNM53me9?p=preview

猜你在找的Angularjs相关文章