我想使用 RouteConfig 将一个变量从我的 AppComponent 传递到 Coursescomponent,但是路由配置中的“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
}
最佳答案
我通过在构造函数中定义动态路由实现了这一点。这是一个例子
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)
}
}
关于typescript - Angular 2 中的 RouteData 可以将变量从父组件传递给路由组件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36108771/