如何将 null 过滤器添加到 mergeMap 下面?
How to add null filter to below mergeMap?
我编写了订阅服务并从中获取价值,然后调用另一个 API。但第一个订阅 API 发生了变化。现在值可以为空。那么,我该如何处理呢?现在代码出现编译错误,oc.id
,或者可以为空。
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 }));
})
)
)));
为了过滤掉 API 现在可能 return 的 null
值,我们希望在调用之间的管道中调用 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;
}
我编写了订阅服务并从中获取价值,然后调用另一个 API。但第一个订阅 API 发生了变化。现在值可以为空。那么,我该如何处理呢?现在代码出现编译错误,oc.id
,或者可以为空。
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 }));
})
)
)));
为了过滤掉 API 现在可能 return 的 null
值,我们希望在调用之间的管道中调用 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;
}