Leon van der Veen
Leon van der Veen

Reputation: 1672

Subscribe to multiple observables

I want to subscribe to multiple observables but the second observable depends on the first one. So from the first one I get a customer id and I need to get all the information from a new 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 is my current code but I don't know how to proceed adding the new observer for getting the customer information. Customer id is present in this.customerAgreement. I can get the customer information by this.customerService.getCustomer(ID).

Upvotes: 0

Views: 1183

Answers (2)

Stanislav Dontsov
Stanislav Dontsov

Reputation: 1741

You need to zip your input with output inside switchMap:

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

Upvotes: 0

ggradnig
ggradnig

Reputation: 14149

Why not just switchMap again? Do you need both, the customer agreement, and the customer information in your subscribe? Then, you should map the result of the first observable onto the result of the second observable using map.

Here is an example:

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

Upvotes: 1

Related Questions