我正在使用Angular2 Material Toolbar,我想將當前頁面標題傳遞給它。Angular 2:如何從另一個組件訪問ActivatedRoute快照數據
我app.component有一個頭組件和當前頁面組件:
@Component({
selector: 'mi-root',
template: `
<mi-header></mi-header>
<router-outlet></router-outlet>
`
})
export class AppComponent {
constructor() {}
}
在我app.routing我有一個自定義的title
屬性路由對象:
const APP_ROUTES: Routes = [
{
path: '',
component: HomeComponent,
data: {
title: 'Home'
}
}, {
path: 'settings',
component: SettingsComponent,
data: {
title: 'Settings'
}
}
];
現在我想從我的header.component訪問data.title
屬性,但不幸的是它是未定義的。我data
對象爲空:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute} from '@angular/router';
@Component({
selector: 'mi-header',
template: `
<md-toolbar color="primary">
<span class="u-ml">{{title}}</span>
</md-toolbar>
`,
styles: []
})
export class HeaderComponent implements OnInit {
title: string;
constructor(private route: ActivatedRoute) {
this.title = this.route.snapshot.data['title'];
}
}
如果我嘗試用同樣的方式來訪問相同的屬性,但是從HomeComponent
或SettingsComponent
正常工作:
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'mi-settings',
template: `
<h1>Welcome to {{title}} screen</h1>
`,
styles: []
})
export class SettingsComponent {
title: string;
constructor(private route: ActivatedRoute) {
this.title = route.snapshot.data['title'];
}
}
所以,我怎麼能訪問route.snapshot.data['title']
從我的HeaderComponent
?
這是因爲'header.component'不是*路由組件*。沒有與之關聯的路由,因此沒有「數據」。你看過*路由器事件*(如[本博客文章](https://toddmotto.com/dynamic-page-titles-angular-2-router-events)中所述) – AngularChef