Reputation: 10932
In my app I have routes with multiple parameters, e.g.
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?
Upvotes: 1
Views: 556
Reputation: 17944
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!!
Upvotes: 1