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.

Upvotes: 3

Views: 9306

Answers (3)

D&#225;vid Leblay
D&#225;vid Leblay

Reputation: 328

An alternative - if defining a function per nircraft's answer is not ideal:
.pipe(filter(x => x != null)) (or even .pipe(filter(x => !!x)))

But this will not have the correct type information by itself.
If the original observable was nullable, like:
const subject = new Subject<boolean | undefined>();
Then you'd expect this to return Observable<boolean>:
subject.pipe(filter(x => x != null))

But instead, it stays Observable<boolean | undefined>.
However, you can fix this with a simple map:
.pipe(filter(x => x != null), map(x => x!))

Upvotes: 0

Jason Landbridge
Jason Landbridge

Reputation: 1402

A more elegant solution from: https://stackoverflow.com/a/51421833/8205497 which does the same as the answer from nircraft

    // add this import on top of your source file
    import { filter } from 'rxjs/operators'

    this.getFoo(fooId)
        .pipe(filter(x) => !!x)
        .subscribe();

Upvotes: 0

nircraft
nircraft

Reputation: 8468

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

Upvotes: 14

Related Questions