arrays - 在 RXJS 中传递给 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$; })
);
}
如果您有问题:
FilteredArrayResponse
是一个通用接口,其data
属性实际上包含数组- 完整的错误信息是
Type 'Observable<Country | Country[]>' is not assignable to type 'Observable<Country[]>'.
- 我的猜测是,它以某种方式
switchMap
将 Observable 的数组与 Observable 的数组混淆了...... - 的返回类型
result.data
始终是数组 - 家庭中的其他操作员
map
表现出相同的行为
解决方案
尝试of(countries)
在switchMap
( import { of } from 'rxjs';
) 中返回。我认为这应该解决它。switchMap
需要切换Observable
到.
import { of } from 'rxjs';
...
switchMap((countries: Country[]) => {
if (countries) {
return of(countries);
}
....
})
推荐阅读
- cassandra - cassandra nodetool gossipinfo 输出中的 RPC_READY 属性是什么
- java - CardView 显示问题中的 RecyclerView 适配器
- javascript - 获取链接以仅发送 POST 请求但实际上并未转到页面
- java - 如何在java中为加权无向图编写toString方法?
- python - 卷积自动编码器图像尺寸误差
- spring - 使用 RabbitMQ 的 Spring 云流
- arrays - 多维数组、Vuex 和突变
- javascript - 如何转义 moment.js 保留字?
- docker - Nextcloud 可信域,通过环境变量自动配置
- css - 响应式图像尺寸