繁体   English   中英

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

[英]How to subscribe to param changes in child route?

我有这些路线

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链接进行导航时有效。

您可以在组件中订阅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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM