首页 > 解决方案 > 如何在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 }));
    })
  )
)));

标签: typescriptrxjsngrxngrx-effectsrxjs-pipeable-operators

解决方案


为了过滤掉nullAPI 现在可能返回的值,我们希望在对和filter的调用之间调用管道中的运算符。switchMapTomergeMap

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;
}

推荐阅读