Investigate activatedRoute observables using rxjs operators

891 views Asked by At

I have a quite simple request: I would like to investigate the activateRoute observables (both paramMap and queryParamMap) - I would like set component variables according to the results of them. Tried doing that using rxjs operators pipe and flatMap, but couldn't result it successfully. See my code:

param1: number;
param2: string;


ngOnInit() {
  this.activatedRoute.paramMap.pipe(
    flatMap(params => {
      this.param1 = +params.get(<name Of Param>);
      return this.activatedRoute.queryParamMap;
    }),
    flatMap(queryParams => {
      this.param2= queryParams.get(<name of query param>);
    })
  ).subscribe(result => /*no need to do anything*/);
2

There are 2 answers

2
Sunil Singh On BEST ANSWER

Actually you should use the switchMap instead of mergeMap since you don't need the result of all the Observable at the end.

param1: number;
param2: string;

ngOnInit() {
  this.activatedRoute.paramMap.pipe(
    switchMap(params => {
      this.param1 = +params.get(<name Of Param>);
      return this.activatedRoute.queryParamMap;
    }),
    map(queryParams => {
      this.param2= queryParams.get(<name of query param>);
    })
  ).subscribe(result => /*no need to do anything*/);
0
pascalpuetz On

If you always want the latest value of both, use combineLatest.

combineLatest(
    this.activatedRoute.paramMap,
    this.activatedRoute.queryParamMap
).subscribe( ([paramMap, queryParamMap]) =>
    // do stuff here
);