[英]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.