Angular 2: Two backend service calls on success of first service

You need to leverage the flatMap operator to call one request after the previous one completed:

this.service.getUserInterests().flatMap(
  (interests) => {
    let params: URLSearchParams = new URLSearchParams();
    params.set('access_token', localStorage.getItem('access_token'));
    return this.http.get('http://localhost:8080/user/selections', {
      search: params
    }).map((res: Response) => res.json());
  }
);

When subscribing to this data flow, you will only receive the result of the last request.

You could use the Observable.forkJoin method to return both. Here is a sample:

var obs = this.service.getUserInterests().flatMap(
  (interests) => {
    return Observable.forkJoin([
      Observable.of(interests),
      this.service.getUserSelections()
    ]);
  }
);

obs.subscribe(
  (result) => {
    var interests = result[0];
    var selections = result[1];
  }
);

Leave a Comment