在 Angular 中,我必须处理以下格式的路线
/sections/{id}?filter={filter}
即我有一个路线参数(id
)和查询参数(filter
)。两个参数都是可选的,因此所有这些路由都是有效的并且正在被监听
/sections/{id}?filter={filter}
/sections?filter={filter}
/sections/{id}
/sections
处理路线时,我需要调用可能昂贵的服务,并提供给定的参数。我可以同时订阅params
and queryParams
路线,但我只想在每次 url 更改时调用该服务一次,以避免任何不必要的调用。
问题是当从/sections/1?filter=active
to /sections/2
两个可观察量都会触发,但我无法控制哪一个先触发。另一方面,当从/sections/1?filter=active
to /sections/1
,或从/sections/1?filter=active
to /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);
});
}
1.订阅路由器事件
您可以订阅路由器events
。这将使您能够访问UrlTree https://angular.io/api/router/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) => { ... });
2.利用combineLatest https://www.learnrxjs.io/operators/combination/combinelatest.html
let params = this.activeRoute.paramMap;
let queryParams = this.activeRoute.queryParamMap;
let navigation = Observable
.combineLatest(params, queryParams, (params, queryParams) => ({ params, queryParams }));
navigation.subscribe((navigation) => { ... });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)