javascript - 如何订阅子路由中的参数变化?

标签 javascript angular typescript

我有这些路线

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/

相关文章:

javascript - Ember.js 路由映射

javascript - Jquery 不在 for 循环中工作,但在单击时工作?

angular - rxjs combineLatest 和 Anguar2 对 Observable 数组的变化检测

javascript - 无法以 Angular 过滤日期

Angular 单元测试 Observable/Subject with Karma

javascript - 无法检查第二个循环内的复选框

javascript - 使用javascript将阿拉伯数字转换为单词

javascript - 将 div 对齐到 Bootstrap4 卡体的底部

node.js - 内置 'net' NodeJS 类型的 TypeScript 定义?

angular - ionic 4/Angular 6 : Nested child routes in tabs