Javascript 如何订阅子路由中的参数更改?

Javascript 如何订阅子路由中的参数更改?,javascript,angular,typescript,Javascript,Angular,Typescript,我有这些路线 const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'explore', component: ExploreComponent, children: [ { path: '', component: ProductListComponent }, { path: ':categorySlug', component: Pro

我有这些路线

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  {
    path: 'explore',
    component: ExploreComponent,
    children: [
      { path: '', component: ProductListComponent },
      { path: ':categorySlug', component: ProductListComponent }
    ]
  }
];
这意味着用户可以转到

/explore
(无类别)

/explore/computers
(类别
计算机

在父级(
ExploreComponent
)中,我希望能够订阅
categorySlug
param更改,并处理事件。我该怎么做

编辑:

我尝试使用以下方式订阅:

this.activatedRoute.firstChild.params.subscribe(console.log)


它给了我想要的东西,但一旦我进入
/explore
(没有分类)它就会消失。它仅在使用
/explore/:categorySlug
链接导航时有效

您可以订阅组件中的
参数
,并获取参数,例如:

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应用程序中使用一种主-细节结构,因此第一条路径指向主路径,第二条路径指向细节,每个路径都有不同的组件,但如果您想对它们使用相同的组件,或者没有这样的主-细节关系,您应该检查参数是否为null。

是的,我正在检查它是否为null。这只打印一次。@FeloVilches一次是什么意思?你能解释一下情况吗?我在事件处理程序中有一个打印,它只打印一次。当我再次改变路线时,什么也没发生。我正在HTML链接中使用
routerLink
。我尝试使用
this.router.events.subscribe(console.log)订阅