【发布时间】:2018-12-18 14:08:02
【问题描述】:
我有 HeaderComponent,它对所有页面都是通用的,并且出现在每个页面上。所以,我为 Header 创建了单独的组件,并使用选择器添加到 app.component.html 中。我创建了两个子页面“Home”和“Second”,并在 app.component.ts 中使用<router-outlet> 对其进行路由
路线
const routes: Routes = [{
path : "", component : HomeViewComponent
},{
path : "second/:id/:category", component : SecondComponent
}];
我在第二个组件中传递参数 id 和 category。
在 HeaderComponent 中我想在路由更改时获取此参数,所以我在 header.component.ts
中执行了以下代码constructor(private router: Router, private route : ActivatedRoute) { }
ngOnInit() {
this.router.events.subscribe((val) => {
// see also
this.route.params.subscribe(params => {
console.log(params);
});
});
}
但是,我无法获得参数。我在控制台中收到 {} 空参数 我也附上了 stackblitz 链接。
https://stackblitz.com/edit/hardik?file=app%2Fapp.routing.module.ts
更新:我在所有页面中都有这个标题组件,而不仅仅是在第二个组件中。所以我不能只把它放在第二个组件中。
【问题讨论】:
-
我找到了这个,希望对您有所帮助:stackoverflow.com/questions/51943663/…
-
我认为参数是空的,因为您的
header-component不在路由器插座内。我不是说你应该把它放在里面,但我说这可能是你无法访问该组件中的参数的原因。 -
你能告诉我们你的头组件需要知道路由参数吗?路由参数总是 id / category 吗?
-
@Florian - 是的,路由参数总是只有 id 和 category。我需要获取此参数值并在标头组件中进行进一步处理。我没有在这里添加这个逻辑,因为这里没有必要。我只想获取参数值,其余的都运行良好
-
@shadowman_93 - 我正在查看您分享的链接。它看起来很有希望,但我仍在研究如何将该代码添加到我的解决方案中
标签: angular router angular-routing angular-activatedroute