Chaining RxJS Observables from http data in Angular2 with TypeScript Chaining RxJS Observables from http data in Angular2 with TypeScript angular angular

Chaining RxJS Observables from http data in Angular2 with TypeScript


For your use case, I think that the flatMap operator is what you need:

this.userData.getUserPhotos('123456').flatMap(data => {  this.userPhotos = data;  return this.userData.getUserInfo();}).subscribe(data => {  this.userInfo = data;});

This way, you will execute the second request once the first one is received. The flatMap operator is particularly useful when you want to use the result of the previous request (previous event) to execute another one. Don't forget to import the operator to be able to use it:

import 'rxjs/add/operator/flatMap';

This answer could give you more details:

If you want to only use subscribe method, you use something like that:

this.userData.getUserPhotos('123456')    .subscribe(      (data) => {        this.userPhotos = data;        this.userData.getUserInfo().subscribe(          (data) => {            this.userInfo = data;          });      });

To finish, if you would want to execute both requests in parallel and be notified when all results are then, you should consider to use Observable.forkJoin (you need to add import 'rxjs/add/observable/forkJoin'):

Observable.forkJoin([  this.userData.getUserPhotos(),  this.userData.getUserInfo()]).subscribe(t=> {    var firstResult = t[0];    var secondResult = t[1];});


What you actually need is the switchMap operator. It takes the initial stream of data (User info) and when completed, replaces it with the images observable.

Here is how I'm understanding your flow:

  • Get User info
  • Get User Id from that info
  • Use the User Id to Get User Photos

Here is a demo. NOTE: I mocked the service but the code will work with the real service.

  ngOnInit() {    this.getPhotos().subscribe();  }  getUserInfo() {    return this.userData.getUserInfo().pipe(      tap(data => {        this.userInfo = data;      }))  }  getPhotos() {    return this.getUserInfo().pipe(      switchMap(data => {        return this.userData.getUserPhotos(data.UserId).pipe(          tap(data => {            this.userPhotos = data;          })        );      })    );  }