我想使用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 }
解决方法
您可以使用共享服务在组件之间共享值.
有关如何实现共享服务的更多详细信息,请参见Global Events in Angular 2.