Angular 2 中的 RouteData 可以将变量从父组件传递给路由组件吗?

Can RouteData in Angular 2 pass variables to routed components from parent component?

我想用RouteConfig从我的AppComponent传递一个变量给Coursescomponent,但是route config中的"data" 属性只能传递常量参数,无法识别"this".有办法吗?

如果不是,将变量传递给路由组件的最佳做法是什么?

@Component({
    selector: 'app',
    template: `
    <router-outlet></router-outlet>
    `,

directives: [ROUTER_DIRECTIVES],
})

@RouteConfig([
    { path: '/courses'
      , name: 'Courses' 
      ,component: CoursesComponent
       ,data:{token:this.token}}  // this doesn't work -- cannot read property "token" of undefined

])

export class AppComponent  {
    token:string;
//I would change the token(string) in this component, and I want to pass this to the routed components

}

您可以使用共享服务在组件之间共享值。

有关如何实施共享服务的更多详细信息,请参阅

或者,您可以注入 Router 并调用其中一个 router.navigateXxx() 函数,您可以在其中传递额外的数据。

我通过在构造函数中定义动态路由实现了这一点。这是一个例子

import {Router,ROUTER_DIRECTIVES} from 'angular2/router';
import {Component} from 'angular2/core';

@Component({
  selector: "app",
  template: '<router-outlet></router-outlet>',
  directives: [ROUTER_DIRECTIVES]
})
export class AppCmp{
  public token:string;
  constructor(private _router:Router){
    var config = [];
    if(!this._router.registry.hasRoute("Courses",AppCmp))
      config.push({ path: '/courses', name: 'Courses',component: CoursesComponent,data:{token:this.token});

    this._router.config(config)
  }
}