2016-11-29 135 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來解決我們的問題,並且它現在可以工作。 –