订阅多个可观察对象

Subscribe to multiple observables

我想订阅多个可观察对象,但第二个可观察对象依赖于第一个。所以从第一个开始,我得到了一个客户 ID,我需要从一个新的 observable 中获取所有信息。

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);
      });

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

为什么不再次 switchMap?您是否需要订阅中的客户协议和客户信息?然后,您应该使用 map 将第一个 observable 的结果映射到第二个 observable 的结果。

这是一个例子:

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);
    });

您需要在 switchMap 中压缩您的输入和输出:

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