How to make nested Observable calls in Angular2

后端 未结 4 2075
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 09:18

I am having some troubles making nested Observable calls. By that I mean a call to a http service that retrieve a user, then getting the id from the user to make another htt

4条回答
  •  無奈伤痛
    2020-12-01 09:50

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

    As of rxjs 5.5 you should use the pipeable operators:

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

提交回复
热议问题