加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 06:51:27 所属栏目:安全 来源:网络整理
导读:所以我刚刚开始使用Angular 2进行编程,并开始学习subscribe,Subject和BehaviorSubject.目前,我有多个订阅来获取存储在我的服务中并发送到组件的值.我的应用程序工作,但我知道这是非常低效的.它在我的组件中失控了: this.threatService.minLimitChange$.subs
所以我刚刚开始使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读