Angular: check an observable that may return null inside switchmap

45 views Asked by At

how to handle the nullity case within a switchmap operator ? I found this workaround, but I get the impression it’s not great to do this:

   this.userService
  .getApporteurId()
  .pipe(
    switchMap((test) =>
      test ? this.mesQuotasService.getQuotas(test) : of({})
    )
  )
  .subscribe((quotas: any) => console.log(quotas));

}

Thanks for help

2

There are 2 answers

0
Yong Shun On

Well, if the current code works, why not.

An alternative is that you may look for iif.

Subscribe to first or second observable based on a condition

import { iif } from 'rxjs';

this.userService
  .getApporteurId()
  .pipe(
    switchMap((test) =>
      iif(() => !!test, this.mesQuotasService.getQuotas(test), of({})
    )
  )
  .subscribe((quotas: any) => console.log(quotas));
}
2
Roksarr On

I am prefer to use filter operator before switchMap like this:

this.userService
  .getApporteurId()
  .pipe(
    filter(test => !!test),
    switchMap((test) => this.mesQuotasService.getQuotas(test))
  )
  .subscribe((quotas: any) => console.log(quotas));