【问题标题】:How to subscribe to param changes in child route?如何订阅子路由中的参数更改?
【发布时间】:2017-09-10 12:53:10
【问题描述】:

我有这些路线

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  {
    path: 'explore',
    component: ExploreComponent,
    children: [
      { path: '', component: ProductListComponent },
      { path: ':categorySlug', component: ProductListComponent }
    ]
  }
];

这意味着用户可以去

/explore(无类别)

/explore/computers(类别computers

从父级 (ExploreComponent),我希望能够订阅 categorySlug 参数更改,当然可以处理事件。我该怎么做?

编辑:

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

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

它给了我我想要的东西,但是一旦我去/explore(没有类别)它就死了。它仅在使用/explore/:categorySlug 链接导航时有效。

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    您可以订阅组件中的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。
    • 这只会打印一次。
    • @FeloVilches 你说的一次是什么意思?你能详细解释一下情况吗?
    • 我在事件处理程序中有一个打印,它只打印一次。当我再次更改路线时,什么也没有发生。我在 HTML 链接中使用routerLink
    • 我尝试使用this.router.events.subscribe(console.log); 订阅,但它给了我很多东西,除了我想要的。
    猜你喜欢
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 2018-07-07
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多