-1

I'm trying to write a service that accesses the spotify api. Therefore this services needs an authorization bearer token. It should get this from another service, which returns an observable. How can I put these together?

My first attempt looks like this:

getSpotifyData(spotifyId: string): Observable<string> {
    let url = "https://api.spotify.com/v1/tracks/" + spotifyId;

    this.config.getSpotifyToken().subscribe(bearer => {
        return this.http.get<string>(url, {headers: {"Authorization": "Bearer " + bearer}});
    });
}

Here the problem is, that this method must return an Observable, wether the config service works or not. This is not the case right now.

Is it possible to combine both observable so that my method can just return a combined observable?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Phil90
  • 138
  • 1
  • 16
  • Possible duplicate of [Angular 7 - nesting Observables](https://stackoverflow.com/questions/56572705/angular-7-nesting-observables) – wentjun Aug 15 '19 at 16:53

1 Answers1

4

You should use switchMap() for that.

getSpotifyData(spotifyId: string): Observable<string> {
    let url = "https://api.spotify.com/v1/tracks/" + spotifyId;

    return this.config.getSpotifyToken().pipe(
        switchMap((bearer: string) => {
            return this.http.get<string>(url, {headers: {"Authorization": "Bearer " + bearer}});
        }),
    );
}

In this case you get the bearer, then use it in the switchMap function and the whole getSpotifyData() function returns an Observable. Then you subscribe to it in the place you need.

igor_c
  • 1,200
  • 1
  • 8
  • 20