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

3

我有这些路由

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链接导航时才能正常工作。
1个回答

0

您可以在组件中订阅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 应用程序中,您会使用一种主细节结构,因此第一个路径指向主要内容,第二个路径指向详细信息,每个都由不同的组件提供,但是如果您想要同时使用相同的组件,或者没有这样的主细节关系,则应检查参数是否为空。


是的,我正在检查它是否为NULL。 - Chris Vilches
这只会打印一次。 - Chris Vilches
@FeloVilches 你说的“once”是什么意思?能否解释一下情况? - Mohsen Kamrani
我在事件处理程序中有一个打印语句,它只会被打印一次。当我再次更改路由时,什么也不会发生。我在HTML链接中使用了routerLink - Chris Vilches
我尝试使用 this.router.events.subscribe(console.log); 进行订阅,但是它除了我想要的东西之外还给了我很多其他东西。 - Chris Vilches

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接