问题
The Angular 2 ES5 cheat sheet says to do this:
var MyComponent = ng.router.RouteConfig([
{ path: '/:myParam', component: MyComponent, as: 'MyCmp' },
{ path: '/staticPath', component: ..., as: ...},
{ path: '/*wildCardParam', component: ..., as: ...}
]).Class({
constructor: function() {}
});
However, I can't figure out how to specify the @Component stuff on that class so that I can actually instantiate it. For example,
ng.router.RouteConfig([...]).Component({})
throws an exception because the result of .RouteConfig doesn't have a .Component method. Similarly, the result of .Component doesn't have a .RouteConfig method. How do you get this set up?
回答1:
I've done the following way which seems to work well.
app.AppComponent = ng.core
.Component({
selector: 'the-app',
template: `
<h1>App!!!</h1>
<a [routerLink]="['Children']">Children</a>
<a [routerLink]="['Lists']">Lists</a>
<router-outlet></router-outlet>
`,
directives:[
app.ListsComponent,
app.ChildrenComponent,
ng.router.ROUTER_DIRECTIVES
]
})
.Class({
constructor: [ng.router.Route, function(_router) {
this._router = _router; // use for navigation, etc
}]
});
app.AppComponent = ng.router
.RouteConfig([
{ path: '/', component:app.ListsComponent, name:'Lists' },
{ path: '/children', component:app.ChildrenComponent, name:'Children' }
])(app.AppComponent);
Since both ng.core.Component and ng.router.RouteConfig are decorators you can write:
app.AppComponent = ng.core.Class(...);
app.AppComponent = ng.core.Component(...)(app.AppComponent);
app.AppComponent = ng.router.RouteConfig(...)(app.AppComponent);
Hope that helps.
回答2:
Here's a possible way I managed to finally get working. I'm open to others posting better solutions:
app.AppComponent = ng.core
.Class({
constructor: [
function() {
}
]
});
app.AppComponent.annotations = [
ng.router.RouteConfig([
{ path: '/', component:app.ListsComponent, name:'Lists' },
{ path: '/children', component:app.ChildrenComponent, name:'Children' }
]).annotations[0],
new ng.core.ComponentMetadata({
selector: 'the-app',
template: '<h1>App!!!</h1>' +
'<a [routerLink]="[\'Children\']">Children</a>' +
'<a [routerLink]="[\'Lists\']">Lists</a>' +
'<router-outlet></router-outlet>',
directives:[
app.ListsComponent,
app.ChildrenComponent,
ng.router.ROUTER_DIRECTIVES
]
})
];
来源:https://stackoverflow.com/questions/34604160/angular-2-routing-in-es5