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

我想使用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.

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

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...