繁体   English   中英

如何等待订阅全部完成?

[英]How to wait subscribe until all finished?

我有4个方法,每个方法在完成之前都会调用。 在所有它们上都设置了以下内容: this.service.next('1');this.service.next('2');this.service.next('3');this.service.next('4'); 我用它来知道哪个方法完成了,所以例如有时我将只执行3个方法,有时执行1个,有时全部执行。 我的问题是我在其他组件上订阅,但每次都在订阅中输入。 我想要的是等待所有方法完成,然后调用this.service.next()

在所有方法中,我对if else语句都有一些逻辑。

这是我的方法之一:

  getOpenConnectionOnLoad(eventSourceId?: any) {
        this.sharedData.block = 'ES';
        this.api.get('/ccm/eventsource/customerESBlock-esId/' + eventSourceId + '?isVpn=true')
            .subscribe(results => {
                this.eventSourceInfo = results['payload'].eventsources[0];
                Object.assign(this.sharedData.customer.eventSourceInfo, this.eventSourceInfo);
                this.setConnectionIds();
                this.customerNames = results['payload'];
                Object.assign(this.sharedData.customer.customerNames, this.customerNames);
                if (this.eventSourceInfo.saggId) {
                    this.openSagg(0, this.eventSourceInfo.saggId);
                }
                if (this.eventSourceInfo.baggId) {
                    this.getBaggById(this.eventSourceInfo.baggId);
                }
                this.showEs();
                this.sharedData.customer.show = 7;

                this.sharedData.callservice.next('2');
            });

在其他组件中,我有这个:

   this.sharedData.callservice.subscribe((data) => {
            console.log('entry ');
        });

然后我只想输入一次,而不要输入4次

看一下forkjoin运算符:

该运算符将所有api调用作为参数传递,并在所有返回数据时恢复。

Observable.forkJoin([
        this.http.get('https://your/api/call/1'),
        this.http.get('https://your/api/call/2'),
 ]).subscribe(results => {
  // results[0] is our result of first api call
  // results[1] is our result of second api call
  console.log(results[1]);
  console.log(results[0]);
});

更新(感谢@HameedSyed)

在rxjs版本6+中,语法已更改:

import {forkJoin} from 'rxjs';

return forkJoin(
    this.http.get('https://your/api/call/1'),
    this.http.get('https://your/api/call/2'));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM