1

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*/);
4

2 回答 2

2

如果您总是想要两者的最新值,请使用 combineLatest。

combineLatest(
    this.activatedRoute.paramMap,
    this.activatedRoute.queryParamMap
).subscribe( ([paramMap, queryParamMap]) =>
    // do stuff here
);
于 2018-11-11T15:48:16.417 回答
1

实际上你应该使用switchMap而不是mergeMap因为你不需要所有 Observable 最后的结果。

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*/);
于 2018-11-11T11:58:13.043 回答