Screeper
Screeper

Reputation: 158

How to properly handle the angular route subscription and then use the parameters for parallel http requests

I try to get the proper solution for the following scenario:

I got an Observable from the subscription to the route parameters. Now if this subscription fires it should start two parallel http requests.

I tried to combine switchMap with forkJoin. Sadly this didn't work. The following code works, but I think I shouldn't use a subscription in a subscription? So what's the proper solution?

this.subscriptions.add(this.route.params.subscribe( params => {
   this.subscriptions.add(forkJoin(
     [this.componentService.getComponentDetails( params.id ), this.planService.getPlanTypes()]
   ).subscribe(
     (data) => {
       console.log(data);
     },
     (error) => {
       console.error('Error loading Form: ', error);
     }
   ));
}));

The subscriptions object is afterwards used to unsubscribe (ngOnDestroy).

Upvotes: 1

Views: 320

Answers (1)

Tomasz Kula
Tomasz Kula

Reputation: 16847

Nested subscriptions are an anti patterns. You can refactor your code to return a single subscription with the use of switchMap operator.

const sub = this.route.paramMap
  .pipe(switchMap(paramMap => {
    const id = paramMap.get('id');
    return forkJoin([
      this.componentService.getComponentDetails(id), 
      this.planService.getPlanTypes()
    ])
  })).subscribe(data => console.log(data))

this.subscriptions.add(sub)

Also, notice how I am using the paramMap instead of params. It is the preferred way of accessing the params in the newest versions of Angular.

Upvotes: 1

Related Questions