2017-02-22 45 views
5

我正在使用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']; 
    } 
} 

如果我嘗試用同樣的方式來訪問相同的屬性,但是從HomeComponentSettingsComponent正常工作:

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

+0

這是因爲'header.component'不是*路由組件*。沒有與之關聯的路由,因此沒有「數據」。你看過*路由器事件*(如[本博客文章](https://toddmotto.com/dynamic-page-titles-angular-2-router-events)中所述) – AngularChef

回答

4
constructor(router:Router, route:ActivatedRoute) { 
    router.events 
    .filter(e => e instanceof NavigationEnd) 
    .forEach(e => { 
     console.log('title', route.root.firstChild.snapshot.data.title); 
    } 
    } 

Plunker example

+0

對於'router.firstChild'它返回我'null'。我知道我做錯了,請給我一個例子,請:) –

+0

然後它可能是一個沒有子路線的葉子段。嘗試'router.root.firstChild' –

+0

不幸的是,它再次返回'null' –

相關問題