typescript - 如何在mergeMap下面添加空过滤器?
问题描述
我编写了订阅服务并获取价值形式,然后调用另一个 API。但是第一个订阅 API 发生了变化。现在值可以为空。那么,我该如何处理呢?现在代码在 , 中出现编译错误oc.id
,或者可以为 null。
getE$ = createEffect(() => this.actions$.pipe(
ofType(ActionType.A),
switchMapTo(this.store.select(selectP)),
mergeMap((oc) => this.reviewService.findByR(oc.id,
new Date(new Date()),
new Date(new Date()), 'A')
.pipe(
mergeMap(d => {
return of(LoadSuccess({ reviews: getReviews(d) }));
}
),
catchError(error => {
return of(LoadFailure({ error: error }));
})
)
)));
解决方案
为了过滤掉null
API 现在可能返回的值,我们希望在对和filter
的调用之间调用管道中的运算符。switchMapTo
mergeMap
import {filter} from 'rxjs/operators';
getE$ = createEffect(() => this.actions$.pipe(
ofType(ActionType.A),
switchMapTo(this.store.select(selectP)),
// remove `null` or `undefined` elements
filter(notNullOrUndefined)
// safely dereference `oc`
mergeMap(oc => this.reviewService.findByR(oc.id,
new Date(new Date()),
new Date(new Date()), 'A'
)
.pipe(
mergeMap(d => of(LoadSuccess({ reviews: getReviews(d) }))),
catchError(error => of(LoadFailure({ error: error })))
)
)));
函数在哪里notNullOrUndefined
测试每个元素并以类型保护的形式传播该信息。这种技术在处理数组时也很有用
export function notNullOrUndefined<T>(x: T | null | undefined): x is T {
return x !== null && x !== undefined;
}
推荐阅读
- d3.js - D3.js:单击时更改条形颜色和另一种 svg 颜色
- wordpress - Woocommerce:仅在独立页面上显示提供的产品
- jwt - Web api 中的 JWT 令牌
- python - ValueError:int() 的无效文字,基数为 10:'1,2,3'
- php - 如何远程访问我的 Google App Engine 实例
- javascript - 如何将随机谷歌图像搜索添加到不和谐机器人
- php - 捕获和处理 PayPal SDK HTTP 异常 PHP yii2
- python - AttributeError: cffi 库 '(pyModulesPath)\_soundfile_data\libsndfile64bit.dll' 没有名为 'sf_wchar_open' 的函数、常量或全局变量
- android - BottomSheet + ViewPager2 拖动隐藏不起作用
- c# - 连接到 SQL Server 数据库