我设置了以下路由系统
export const MyRoutes: Routes = [
{path: '', redirectTo: 'new', pathMatch: 'full'},
{path: ':type', component: MyComponent}
];
并拥有以下导航系统
goToPage('new');
goToPageNo('new', 2);
goToPage(type) {
this.router.navigate([type]);
}
goToPageNo(type, pageNo) {
this.router.navigate([type], {queryParams: {page: pageNo}});
}
示例 URL 如下所示
http://localhost:3000/new
http://localhost:3000/new?page=2
http://localhost:3000/updated
http://localhost:3000/updated?page=5
有时他们有可选查询参数(页面)
现在我需要读取路由参数和查询参数
ngOnInit(): void {
this.paramsSubscription = this.route.params.subscribe((param: any) => {
this.type = param['type'];
this.querySubscription = this.route.queryParams.subscribe((queryParam: any) => {
this.page = queryParam['page'];
if (this.page)
this.goToPageNo(this.type, this.page);
else
this.goToPage(this.type);
})
})
}
ngOnDestroy(): void {
this.paramsSubscription.unsubscribe();
this.querySubscription.unsubscribe();
}
现在这没有按预期工作,访问没有 queryParams 的页面可以工作,然后我访问带有 queryParams 的页面“goToPageNo”被多次调用,因为我在路由参数中订阅 queryParams。
我查看了 Angular 2 文档,他们没有任何示例或代码可以同时实现对路由参数和查询参数的订阅。
有什么办法可以正确地做到这一点?有什么建议吗?
最佳答案
通过在订阅前使用 Observable.combineLatest
组合可观察对象,我设法获得了对 queryParams 和 Params 的单一订阅。
例如。
var obsComb = Observable.combineLatest(this.route.params, this.route.queryParams,
(params, qparams) => ({ params, qparams }));
obsComb.subscribe( ap => {
console.log(ap.params['type']);
console.log(ap.qparams['page']);
});
关于angular - 在 Angular 2 中订阅路由参数和查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40699229/