问题描述
我设置了以下路由系统
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/new?page=2
http://localhost:3000/updated
http://localhost:3000/updated
http://localhost:3000/updated?page=5
http://localhost:3000/updated?page=5
有时他们有可选 queryParams(页面)
Sometimes they have optional queryParams (page)
现在我需要阅读路由参数和查询参数
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.
Now this is not working as expected, visiting pages without queryParams works, then of I visit a page with queryParams "goToPageNo" gets called multiple times, as I am subscribing to queryParams inside route params.
我查看了 Angular 2 文档,他们没有任何示例或代码可以同时实现对路由参数和查询参数的订阅.
I looked at the Angular 2 documentation, they do not have any example or codes where a subscription to both route params and queryParams is implemented at the same time.
有什么办法可以正确地做到这一点?有什么建议吗?
Any way to do this properly? Any suggestions?
推荐答案
对于 Angular 6+
For Angular 6+
import { combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
...
combineLatest(this.route.params, this.route.queryParams)
.pipe(map(results => ({params: results[0].xxx, query: results[1]})))
.subscribe(results => {
console.log(results);
});
xxx
来自您路线的位置
{path: 'post/:xxx', component: MyComponent},
这篇关于在 Angular 2 中同时订阅路由参数和查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!