目前我正在为我的应用程序使用此路由设置:
{
path: ':group',
component: ArticleListComponent,
children: [{
path: ':subgroup',
component: ArticleListComponent,
children: [{
path: ':chapter',
component: ArticleListComponent,
children: [{
path: ':section',
component: ArticleListComponent,
children: [
]
}
]
}
]
}
]
},
因为模板和代码不会改变,所以我使用相同的组件来列出文章,但是我想使用url来过滤这些文章。该应用程序应该使用路由参数而不是获取参数。使用这些参数,我想调用一个 API 来获取属于此 url 的文章:/group1/subgroup1/chapter1/section1。
问题是我只能通过以下代码获取这些参数:
const params = this.route.snapshot.params;
// {group: "group1"}
const params = this.route.parent.snapshot.params;
// {}
const params = this.route.firstChild.snapshot.params;
// {group: "group1", subgroup: "subgroup1"}
如何一次获取所有这些参数?
最佳答案
使用查询参数而不是参数。它将大大简化您的路由配置。
routing.ts
{
path: '',
component: ArticleListComponent
}
文章列表.component.ts
constructor(route: ActivatedRoute) {
route.queryParams.pipe(
map(({ group, subgroup, chapter, section }) =>
({ group, subgroup, chapter, section }))
).subscribe( ... )
}
关于Angular 6 路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51475877/