Angular:如何从另一个组件访问ActivatedRoute快照数据

时间:2017-02-22 17:45:08

标签: angular angular-material

我正在使用Angular2 Material Toolbar,我想将当前页面标题传递给它。

我的 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

1 个答案:

答案 0 :(得分:6)

  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