简体   繁体   中英

Angular 2 router evaluating multiple route parameters

In my app I have routes with multiple parameters, eg

http://localhost:3000/department/6/employee/45/sales?from=20160921&to=20160928

How do I best approach evaluating these parameters? I can subscribe to params and queryParams of the ActivatedRoute ,

this.route.params.subscribe(params => ...load data for params);
this.route.queryParams.subscribe(queryParams=> ...load data for queryParams);

However, this will trigger load twice, of course. Also, I always need both pieces of information, for instance sales and from / to from the above example.

So the above code becomes

this.route.params.subscribe(params => {
    let queryParams = this.route.snapshot.queryParams;
    ...load data for params/queryParams
}

this.route.queryParams.subscribe(queryParams => {
    let params = this.route.snapshot.params;
    ...load data for params/queryParams
}

And I still haven't got a solution to the problem of triggering load twice.

To make matters worse, I also need to figure out just how many levels I need to go up in my ActivatedRoute , so it's not unusual to see

this.route.parent.parent.parent.params.subscribe(...)

Ugh. And that breaks down for a lazy loaded component anyway. In any case, it's a lot of boilerplate code just to retrieve a handful of route parameters.

Am I doing this wrong? Is there a recommended way of going about this?

You may try below,

paramSubscription = Observable.forkJoin(
  this.route.params,
  this.route.queryParams,
  this.route.parent.parent.parent.params
).subscribe(res => {
   this.combinedParams = { params :res[0], queryParams :res[1], ancestorParam : res[2] };
   // Load data
 });

// unsubscribe from the subscription
ngOnDestroy = () => {
    this.paramSubscription.unsubscribe();
}

Please note I have not tested this code yet.

Hope this helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM