所以我刚刚开始使用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()所需的所有值并运行该函数 once . 我非常感谢有关如何使用concat,merge或forkJoin来组合我的订阅的任何帮助或解释 . 谢谢!
1 回答
您可以使用
Observable.combineLatest
将2个可观察流合并为一个:工作人员:http://plnkr.co/edit/mmCzEmdKexpaWNM53me9?p=preview