In Angular I have to process a route in the format
/sections/{id}?filter={filter}
i.e. I have a route parameter (id
), and a query parameter (filter
). Both parameters are optional, so all of these routes are valid and being listened to
/sections/{id}?filter={filter}
/sections?filter={filter}
/sections/{id}
/sections
When handling a route I need to call a potentially expensive service, providing the parameters given. I can subscribe to both the params
and queryParams
of the route, but I want only to call the service once per url change, avoiding any unneeded calls.
The problem is that when moving from /sections/1?filter=active
to /sections/2
both observables will trigger, and I cannot control which one will trigger first. On the other hand, when moving from /sections/1?filter=active
to /sections/1
, or from /sections/1?filter=active
to /sections/2?filter=active
, only one will be triggered.
Is there any sane way to know when the last subscription triggers, so that I can avoid sending unneeded server calls?
The test code so far looks something like:
constructor(private activeRoute: ActivatedRoute, private dataService: dataService) {
this.activeRoute.paramMap.subscribe((params: ParamMap) => {
console.log("triggering route params subscription");
this.section = params.get("id");
this.dataService.runSlowQuery(this.section, this.filter);
});
this.activeRoute.queryParamMap.subscribe((queryParams: ParamMap) => {
console.log("triggering query params subscription");
this.filter = queryParams.get("filter");
this.dataService.runSlowQuery(this.section, this.filter);
});
}