0

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

Olivier
  • 343
  • 2
  • 16

2 Answers2

3

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));
Roksarr
  • 66
  • 1
  • I've tried it, but doesn't work for me... – Olivier May 02 '23 at 07:57
  • Can you create a StackBlitz example to better demonstrate what you're suggesting? It would be really helpful to see your code in action and understand how it all fits together. – Roksarr May 02 '23 at 10:48
0

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));
}
Yong Shun
  • 35,286
  • 4
  • 24
  • 46