簡體   English   中英

傳入 RXJS 中的 switchMap() 時對象數組的奇怪行為

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

我有一個簡單的目標,即創建一個可輸出世界上所有國家/地區列表的 observable。 observable 的類型是Country[] ,即存儲值的類型是對象數組。 但是,當傳遞給switchMap ,它會神奇地轉換為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$; })
    );
  }

如果您有疑問:

  • FilteredArrayResponse是一個通用接口,其data屬性實際上包含數組
  • 完整的錯誤消息是Type 'Observable<Country | Country[]>' is not assignable to type 'Observable<Country[]>'. Type 'Observable<Country | Country[]>' is not assignable to type 'Observable<Country[]>'.
  • 我的猜測是,不知何故switchMap將可觀察的數組與可觀察的數組混淆了......
  • result.data的返回類型始終是一個數組
  • map系列中的其他運算符表現出相同的行為

嘗試在switchMap返回of(countries)import { of } from 'rxjs'; )。 我認為這應該解決它。 switchMap需要切換到Observable

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM