我需要从子路径视图设置 Headers Headers ...
我有父组件:
@Component({
selector: 'parent-component',
template: `
<header>{{headerTitle}}</header>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
{ path: '/link1', name: 'Link1', component: Link1Component, useAsDefault: true },
{ path: '/link2', name: 'Link2', component: Link2Component },
])
export class ParentComponent {
public sharedHeaderTitle: string;
constructor(public router: Router) { }
}
有一个childs路由选项卡:
@Component({
template: '<div></div>'
})
export class Link1Component {
public headerTitle: string;
constructor() {
this.headerTitle = "Link1 page";
}
}
还有一个
@Component({
template: '<div></div>'
})
export class Link2Component {
public headerTitle: string;
constructor() {
this.headerTitle = "Link2 page";
}
}
它如何在亲子中发现here但它不适用于路由......
什么是最好的方法呢?
已解决
我找到了一个解决方案,认为这是最好的方法:
http://plnkr.co/edit/LYTXmY9Fwm8LwumICWDT
2 回答
您可以创建一个单独的服务,只要您需要处理 Headers (要么更改它或获得它的值),就会注入该服务 .
参考:https://angular.io/docs/ts/latest/tutorial/toh-pt4.html
Link1Component
和Link2Component
需要与ParentComponent
进行通信 . 由于它们被限制在路由器插座中,我不确定除了订阅路由器事件之外是否可能这样做(参见How to detect a route change in Angular 2?)我还会考虑更改设计并将设置 Headers 的责任移到
ParentComponent
,即ParentComponent
在发出router.navigate(['LinkXComponent']
命令之前设置 Headers .我希望这有帮助