How to make nested Observable calls in Angular2

You should read up on rxjs’s operators a little. Your examples are very verbose and use flatMap and map in a way they’re not supposed to be used. Also your first example can’t work, because you’re not subscribing to the Observable.

This will do what you need:

ngOnInit() {
    this.userService.getUser().pipe(
        tap(u => this.user = u),
        flatMap(u => this.userService.getPreferences(u.username))
      ).subscribe(p => this.preferences = p);
}

legacy:

Before version 5.5 rxjs exclusively used prototype-based operators.
This code is functionally equivalent to the above:

ngOnInit() {
    this.userService.getUser()
        .do(u => this.user = u) //.do just invokes the function. does not manipulate the stream, return value is ignored.
        .flatMap(u => this.userService.getPreferences(u.username))
        .subscribe(p => this.preferences = p);
}

Leave a Comment