在Angular中我必须以
格式处理路线/sections/{id}?filter={filter}
即。我有一个路由参数(id
)和一个查询参数(filter
)。这两个参数都是可选的,因此所有这些路由都是有效的并且正在被监听
/sections/{id}?filter={filter}
/sections?filter={filter}
/sections/{id}
/sections
处理路线时,我需要调用潜在的昂贵服务,提供给定的参数。我可以订阅路由的params
和queryParams
,但我只想在每个网址更改时调用一次服务,避免任何不必要的调用。
问题是当从/sections/1?filter=active
移动到/sections/2
时,两个可观察量都会触发,我无法控制哪个会先触发。另一方面,当从/sections/1?filter=active
移动到/sections/1
,或从/sections/1?filter=active
移动到/sections/2?filter=active
时,只会触发一个。
是否有任何理智的方式来了解最后一个订阅何时触发,以便我可以避免发送不需要的服务器调用?
到目前为止,测试代码类似于:
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);
});
}
答案 0 :(得分:3)
您可以订阅路由器events
。这将使您可以访问UrlTree
对象,从而提供更大的灵活性。
import { Router, UrlTree, NavigationEnd } from '@angular/router';
...
constructor(private router: Router) {}
...
let navigation = this.router.events
.filter(navigation => navigation instanceof NavigationEnd)
.map((navigation) => {
let urlTree = this.router.parseUrl(navigation['url']);
let queryParams = urlTree.queryParams;
let segments = urlTree.root.children['primary'] ? urlTree.root.children['primary'].segments : null;
return { queryParams: queryParams, segments: segments }
});
navigation.subscribe((navigation) => { ... });
combineLatest
let params = this.activeRoute.paramMap;
let queryParams = this.activeRoute.queryParamMap;
let navigation = Observable
.combineLatest(params, queryParams, (params, queryParams) => ({ params, queryParams }));
navigation.subscribe((navigation) => { ... });