2

I am attempting to follow the tutorial on how to get route parameters in the Angular Routing documentation.

I am able to get the route parameters when using subscribe.

this.getRouteParams$ = this.route.params.subscribe(params => {
  // Works
  console.log(params);
});

However according to the documentation it is best practice to use switchMap. I am unable to get the switchMap example to work in my code and I am not sure why.

import { switchMap } from 'rxjs/operators';

this.getRouteParams$ = this.route.params.pipe(
  switchMap(params => {
    // Does not work
    console.log(params);
    // How to check params here and then subscribe to other observables conditionally
  })
);

The ultimate goal is to use switchMap to call other observables conditionally based on the value of the route parameters after they are received and validated. However I am unable to get even the first switchMap statement to work correctly as shown above.

pengz
  • 2,279
  • 3
  • 48
  • 91

2 Answers2

3

You need to subscribe to evaluate the Observable and to call another observable conditionally as per param, do like this:

import { switchMap } from 'rxjs/operators';

this.getRouteParams$ = this.route.params.pipe(
  switchMap(params => {
    console.log(params);
    // How to check params here and then subscribe to other observables conditionally
    //here you can check the params and return the another observable like this:

    //BELOW code is just to show how to return another observable conditionally
    //Change it as per your logic
    const p = params['id']; //i am assuming that your param name is `id`; 
    if(p === 100) {
       return this.anotherObservable()
                  .pipe(
                     tap(r => {
                       //DO whaterver you want to do with the response of the observable
                       console.log(r);
                     })
                   );
    } else {
       return of(someThingAsPerYourLogic);
    }
  })
).subscribe();
user2216584
  • 5,387
  • 3
  • 22
  • 29
2

//this will work
import { switchMap } from 'rxjs/operators';

this.getRouteParams$ = this.route.params.pipe(
  switchMap(params => {
    // Does not work
    console.log(params);
    // How to check params here and then subscribe to other observables conditionally
  })
).subscribe(item=>{
console.log(item
})
Pari Baker
  • 696
  • 4
  • 19
  • 2
    subscribing will let you see the end result, if you want to check the value within the pipe you can console.log() within the params, but all of your logic will go in pipe, subscribing to the observable is what 'executes' it per se – Pari Baker Jul 17 '19 at 21:50