Search code examples
javascriptangulartypescriptrxjsobservable

How to check null response in .pipe(map) Rxjs operators?


getDetailsById(eId: number): Observable<Details> {
  return this.api.post('detailsapi', cacheOptions, { Id: eId })
    .pipe(
      map((eDetails: any) => ({
        id: eDetails.eId,
        subDetails: this.mapSubDetails(eDetails.eSubDetails || [])
      })),
      catchError((err) => {
        const template: Template = {   
          id: 0,
          subEquipment: []
        };
        return Observable.throw(err)
      })
    );
}

I'd like to check in above code if eDetails is null or not. If null then I want to stop all the calls in Observable.forkJoin.


Solution

  • You can add a filter in the pipe:

    .pipe(filter(isNotNull))
    

    And use a typeguard for the same:

    export function isNotNull<T>(value: T): value is NonNullable<T> {
      return value != null;
    }