Yeysides
Yeysides

Reputation: 1292

How to pass Observable value to multiple Observable calls asynchronously?

I want to take a value emitted from one observable and use that value as a parameter to make two http calls, then subscribe to a concatenated result of those two calls, though it doesn't have to be concatenated. I tried to use the .zip operator in this case but I can't seem to get it working. Only the .getSymbolData call is being made. Is there another operator that I should be utilizing?

   this.symbolSearchService.getSymbolData('cmcsa')
      .zip(stock => {
        console.log('stock', stock); <-- looks good
        this.symbolSearchService.getResearchReportData(stock);
        this.symbolSearchService.getPGRDataAndContextSummary(stock);
      })
      .subscribe(
        res => {
          console.log('res', res); <-- undefined
        },
        err => this.sharedService.handleError
      );

EDIT: I forgot to mention I would like to preserve the value from the initial observable. So I want to do this.stock = stock somewhere.

Upvotes: 0

Views: 765

Answers (1)

Eeks33
Eeks33

Reputation: 2315

What you're looking for is the switchMap and combineLatest operators. It allows you to return a new observable.

    this.symbolSearchService.getSymbolData('cmcsa')
      .switchMap(stock => {
        this.stock = stock;
        return Observable.combineLatest(
          this.symbolSearchService.getResearchReportData(stock),
          this.symbolSearchService.getPGRDataAndContextSummary(stock)
        })
      .subscribe(
        values => {
          console.log('values', values);
        },
        err => this.sharedService.handleError
      );

Upvotes: 1

Related Questions