简体   繁体   中英

Strange behaviour of an array of objects when passed into switchMap() in RXJS

I have a simple goal of creating an observable that emits a list of all the countries in the world. The type of the observable is Country[] , ie the store value is typed as an array of objects. However, when passed to switchMap , it magically gets converted into type Country . I have no idea what causes this behavior and if it is not, by chance, on my side. Here is the function in question:

public getAllCountries(): Observable<Country[]> {

      const getAppState = createFeatureSelector<ServicesState>('services');
      const getCountries = createSelector( getAppState, (state: ServicesState): Country[] => state.countries);
      // as you can see, this is the NGRX store slice that must be of type Observable<Country[]>
      const countriesFromStore$ = this.store.pipe(select(getCountries));

      return countriesFromStore$.pipe(
        // this is the switchMap that causes the error
        switchMap( countries => {
        // this is the return statement that somehow converts an array of objects into a single object??
        if (countries)  { return countries; }
        const countriesFromServer$: Observable<Country[]> = this.http.get<FilteredArrayResponse<Country>>
           (this.baseUrl, this.config.httpGetJsonOptions).pipe(
               tap( result => this.store.dispatch( new LoadCountriesAction(result.data)) ),
               map( result => result.data)
           );
        return countriesFromServer$; })
    );
  }

In case you have questions :

  • FilteredArrayResponse is a generic interface with data attribute actually containing the array
  • The full error message is Type 'Observable<Country | Country[]>' is not assignable to type 'Observable<Country[]>'. Type 'Observable<Country | Country[]>' is not assignable to type 'Observable<Country[]>'.
  • My guess is that somehow switchMap confuses an Observable of Arrays with an Array of Observables...
  • The return type of result.data is always an array
  • Other operators from the map family exhibit the same behaviour

Try returning of(countries) in the switchMap ( import { of } from 'rxjs'; ). I think that should fix it. The switchMap needs to switch to an Observable .

import { of } from 'rxjs';
...
switchMap((countries: Country[]) => {
  if (countries) {
    return of(countries);
  }
  ....
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM