订阅多个可观察物

时间:2018-08-28 09:35:59

标签: angular rxjs observable subscribe

我想订阅多个可观察变量,但是第二个可观察变量取决于第一个。因此,从第一个开始,我得到了一个客户ID,我需要从一个新的可观察对象中获取所有信息。

this.taskService
      .get(this.$state.params.taskId)
      .pipe(
        switchMap((taskDetails: IGetTask) => this.taskService.getAgreement(taskDetails.taskParameters.customerAgreementId)),
        tap(customerAgreement => this.customerAgreement = customerAgreement)
      )
      .subscribe((data: any) => {
        this.signees = new SignatoryDetails(data);
        this.customerDetails = new CustomerDetails(data);
      });

这是我当前的代码,但我不知道如何继续添加新观察者以获取客户信息。客户ID存在于this.customerAgreement中。我可以通过this.customerService.getCustomer(ID)获取客户信息。

2 个答案:

答案 0 :(得分:1)

为什么不只是switchMap?您同时需要客户协议和客户信息吗?然后,您应该使用map将第一个可观察到的结果映射到第二个可观察到的结果。

这里是一个例子:

this.taskService
    .get(this.$state.params.taskId)
    .pipe(
        switchMap((taskDetails: IGetTask) => this.taskService.getAgreement(taskDetails.taskParameters.customerAgreementId)),
        tap(customerAgreement => this.customerAgreement = customerAgreement),
        switchMap(customerAgreement => this.customerService.getCustomer(customerAgreement.id).pipe(
            map(customerInformation => ({customerInformation: customerInformation, customerAgreement: customerAgreement}))))
    )
    .subscribe((data: any) => {
        let customerAgreement = data.customerAgreement;
        let customerInformation = data.customerInformation;

        this.signees = new SignatoryDetails(data);
        this.customerDetails = new CustomerDetails(data);
    });

答案 1 :(得分:0)

您需要在switchMap中将输入与输出压缩在一起:

switchMap((taskDetails: IGetTask) =>
        Observable.zip(this.taskService.getAgreement(taskDetails.taskParameters.customerAgreementId),
                        Observable.Of(taskDetails.taskParameters.customerAgreementId)))