我有这些路线
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{
path: 'explore',
component: ExploreComponent,
children: [
{ path: '', component: ProductListComponent },
{ path: ':categorySlug', component: ProductListComponent }
]
}
];
这意味着用户可以转到
/explore
(无类别)
或
/explore/computers
(类别计算机
)
从父级 (ExploreComponent
) 中,我希望能够订阅 categorySlug
参数更改,并当然处理该事件。我怎样才能做到这一点?
编辑:
我尝试使用以下方式订阅:
this.activatedRoute.firstChild.params.subscribe(console.log);
它给了我我想要的东西,但是一旦我进入 /explore
(没有类别),它就消失了。它仅在使用 /explore/:categorySlug
链接导航时有效。
最佳答案
您可以订阅组件中的params
并获取参数,例如像这样:
import { Router, ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe(params => {
this.categorySlug= params['categorySlug '];
});
// do something with this.categorySlug
}
旁注:通常,您在 Web 应用程序中使用一种主详细信息结构,因此第一个路径指向主信息,第二条路径指向详细信息,每个路径都有不同的服务组件,但如果您想为它们使用相同的组件,或者不存在这样的主从关系,则应该检查该参数是否为空。
关于javascript - 如何订阅子路由中的参数变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46137270/