当传入 RXJS 中的 switchMap() 时,对象数组的奇怪行为

pet*_*aja 0 arrays observable rxjs typescript switchmap

我有一个简单的目标,即创建一个可观察的对象,以发出世界上所有国家/地区的列表。observable 的类型是Country[],即存储值的类型为对象数组。然而,当传递给 时switchMap,它会神奇地转换为 type Country。我不知道是什么原因导致这种行为,如果它不是偶然的,在我这边。这是有问题的函数:

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$; })
    );
  }
Run Code Online (Sandbox Code Playgroud)

如果您有疑问:

  • FilteredArrayResponse是一个通用接口,其data属性实际上包含数组
  • 完整的错误消息是Type 'Observable<Country | Country[]>' is not assignable to type 'Observable<Country[]>'.
  • 我的猜测是,不知何故switchMap混淆了数组的可观察值和可观察值的数组......
  • 的返回类型result.data始终是数组
  • 家族中的其他经营者也map表现出同样的行为

Ali*_*F50 5

尝试of(countries)switchMap( import { of } from 'rxjs';) 中返回。我认为这应该解决它。需要switchMap切换到Observable.

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