Search code examples
javascriptangularangular7switchmap

Why can't I access property when using switchMap?


I have a method attached to a button. A user enters their name in an input, and when the button is clicked, information from that user is displayed. How I am planning to do that is explained below..

I am trying to pass in a value from one Observable into another Observable. The value I am trying to get from the first Observable is an ID that is then used within the second Observable.

My current method of doing this is using the switchMap operator. However, when passing in the ID from the first Observable into the second, I am seeing 'undefined' in my console..

I am thinking that either I am not accessing the ID correctly when calling the first Observable.. Or I should not use switchMap ??

It's also weird and I thought I was close because using Object.keys(player)['0'] I can get the first Object key (Data). But using Object.keys(player)['0'].id; is undefined :/

This is response object I am trying to get the ID from:

Imgur

click function within my component:

click() {
  this.playerService.getPlayer(this.searchString).pipe(
      switchMap(player => {
        let ID = Object.keys(player)['0'];
        let anotherID = ID['0'].id;

        return this.playerService.getSeasonStats(anotherID);
      }))
    .subscribe(id => this.player = id)
}

Service with getPlayer method and getSeasonStats method:

getPlayer(query: string):Observable<Player> {
  let getHeaders = new HttpHeaders({'Authorization':'Bearer API_Key', 'Accept': 'application/vnd.api+json'}); 
  return this.http.get<Player>(`https://api.com/shards/steam/players?filter[playerNames]=${query}`, {
    observe:'body',
    responseType: 'json',
    headers: getHeaders
  });
}


getSeasonStats(id: string):Observable<SeasonStats[]> {
  let getHeaders = new HttpHeaders({'Authorization':'Bearer API_Key', 'Accept': 'application/vnd.api+json'}); 
  return this.http.get<SeasonStats[]>(`https://api.com/shards/steam/players/${id}/seasons/division.bro.official.pc-2018-04`,  {
    observe:'body',
    responseType: 'json',
    headers: getHeaders
  });
}

Solution

  • Your problem is:

    let ID = Object.keys(player)['0'];
    let anotherID = ID['0'].id;
    

    the line Object.keys(player)['0'] returns you "data" as string, now doing ['0'] you get "d"... so your result is "d".id => undefined

    Maybe you need to do something like:

    let playerData = player["data"][0];
    let anotherID = playerData.id;