使用Angular 2路由器服务更改页面标题

时间:2016-11-29 16:50:40

标签: angular angular2-routing router

我正在尝试使用路由器服务更改页面标题。但是,变量始终无法从路由器服务获取值。有人可以帮忙吗?谢谢!

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始终在控制台输出中显示“undefined”,这意味着它根本没有从路由器服务获取任何值。我在这里错过了吗?谢谢!

1 个答案:

答案 0 :(得分:0)

数据存在于附加到路径的组件上。因此,加载VtcComponent的父路由无法访问传递到子路由的数据,除非您使用firstChild property来访问路由树上的第一个子节点。例如:

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