0

I'm still trying to get my head around rxjs in Angular, I still don't fully understand pipes and operators. I need help with this scenario and what would be the correct way to do it (allready tried a dirty way and accomplished it but didn't feel right).

I want to fetch some data when loading a page, referenced by a param in the route. There are two scenarios, if it has an id it should save it to a local variable, then, fetch the data and process it. If it does not have any id param, it should skip the data fetch. The code I have is this:

        this.activatedRoute.params.pipe(
            //I want to save params.id to this.id here
            //I dont want to execute the switchmap if params.id is empty
            switchMap(params => this.establishmentService.getEstablishment(params.id))
        ).subscribe(/* process data */);

How do I access the data returned from activatedRoute params for the local variable and how do I avoid the getEstablishment function if that param is null? Thank you.

3 Answers3

1

You need to use tap and filter for that.

this.activatedRoute.params.pipe(
  tap(params => this.id = params.id), // saving id
  filter(params => !!params.id), // ignoring service until we have an id
  switchMap(params => this.establishmentService.getEstablishment(params.id)),
).subscribe(servieResult => {});
satanTime
  • 12,631
  • 1
  • 25
  • 73
0

An alternative could the use of the expand as described under https://stackoverflow.com/a/54514832/6585002

Ceddaerrix
  • 304
  • 1
  • 14
-1

To begin with, you can easily avoid executing getEstablishment with a ternary operator to check if params.id is null

 this.activatedRoute.params.pipe(
            switchMap(params => params.id ? this.establishmentService.getEstablishment(params.id)) : params
        ).subscribe(/* process data */);
Balastrong
  • 4,336
  • 2
  • 12
  • 31