Search code examples
angularrxjsobservablerxjs5behaviorsubject

Providing a parameter from an Observable to a function that returns an Observable


I have a function with the following signature:

fetchUserCar(userId: string): Observable<Car>

But to get the userId parameter, I have to call a function that I cannot edit, which is the following:

private user$ = new ReplaySubject < User > ();
public getUser(): Observable < User > {
  return this.user$.asObservable().share();
}

How do I go about in doing this?


Solution

  • You need to call getUser() and then flatMap the call to fetchUserCar passing the user id obtained from getUser().

    fetchCar(): Observable<Car> {
        this.userService.getUser()
            .flatMap(user => this.carService.fetchUserCar(user.id))
    }