2016-11-29 112 views
0

我试图通过使用路由器服务来更改页面标题。但是,变量总是无法从路由器服务获取值。谁能帮忙?谢谢!使用Angular 2路由器服务更改页面标题

vtc.route.ts

const routes: Routes = [ 
{ 
    path: '', component: VtcComponent, children: [ 
     { path: '', redirectTo: "step1", pathMatch: "full" }, 
     { path: 'step1', component: Step1Component, data:{pageHeader: 'Step1'} }, 
     { path: 'step2', component: Step2Component, data:{pageHeader: 'Step2'} }, 
...... 
    ] 
} 

];

vtc.component.ts

export class VtcComponent implements OnInit { 
private subscription: Subscription; 
private subscription1: Subscription; 
webLinkParameter: string; 
brokerInformation: IBroker; 
authInfo: IAuth; 
pageHeader: string; 
constructor(private dataService: VtcDataService, private brokerService: BrokerService, private activatedRoute: ActivatedRoute, private authService: AuthService) { } 

ngOnInit() { 
    this.subscription = this.activatedRoute.queryParams.subscribe(
     (param: any) => { 
      this.webLinkParameter = param['brokerid']; 
     }); 

    //This is the part that the variable trying to get value from router service 
    this.subscription1 = this.activatedRoute.data.subscribe(res => {this.pageHeader = res['pageHeader']}); 

    console.log("pageHeader: " + this.pageHeader); 
.... 
} 

变量pageHeader始终显示在控制台输出,这意味着它没有从路由器服务的任何价值可言“不确定”。我在这里错过了什么吗?谢谢!

回答

0

数据存在于连接到路由的组件上。因此,加载VtcComponent的父路由不能访问传入子路由的数据,除非您使用firstChild property访问路由树上的第一个子节点。如:

this.subscription1 = this.activatedRoute.firstChild.data.subscribe(d => this.pageHeader = d['pageHeader']) 
+0

谢谢您的建议!我们决定使用PageService来解决我们的问题,并且它现在可以工作。 –