Search code examples
typescriptrxjsngrxngrx-effectsrxjs-pipeable-operators

How to add null filter to below mergeMap?


I wrote subscribe service and get value form that and after that call another API. but the first subscription API changed. Now value can be null. so, how can I handle that?. Now code came compile error in, oc.id, or can be 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 }));
    })
  )
)));

Solution

  • To filter out the null values that the API may now return, we want to place a call to the filter operator in our pipeline between the calls to switchMapTo and 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 })))
            )
        )));
    

    Where notNullOrUndefined is a function tests each element and propagates that information in the form of a type guard. This technique is also useful when working with arrays

    export function notNullOrUndefined<T>(x: T | null | undefined): x is T {
        return x !== null && x !== undefined;
    }