Search code examples
angularrxjsswitchmap

RxJS: Extracting an array of values from complex json via http


Angular 10

(Simplified)

I have an http get that returns a country and a list of States in the country:

   {"id":1,
    "countryMeta": 
        {"statesList": 
             [
               {"name":"AB","value":"AB"},
               {"name":"CA","value":"CA"},
             ]}
     }

I am trying to get a list of states from this object and put it into a NameValue array, but I only get 1 state out and it's not an array. Shouldn't switchMap do that?

    states$ = this.myHttpService.get().pipe(switchMap((x) => x.countryMeta.statesList));

Then consumed:

*ngFor="let state of states$ | async"

Solution

  • I think you need map.

    import { map } from 'rxjs/operators';
    states$ = this.myHttpService.get().pipe(map((x) => x.countryMeta.statesList));
    

    switchMap switches to a new observable, map transforms current observable.