这是我刚刚使用Angular-CLI发现的一种非常奇怪的行为。已在https://github.com/angular/angular-cli/issues/4234处提出了一张票。
使用router.resetConfig()方法动态添加路由时似乎存在错误。我不确定它是否是Angular-CLI,Angular编译器,Angular Router或Webpack中的错误。我只是想分享这个问题,这样你就不会把你的头撞到墙上。
这是设置:
## routes.json
[
{ "path": "contact", "loadChildren": "./contact/contact.module#ContactModule" }
]
## RouterService.ts
getRotues() {
return this._http.get('routes.json')
.map((res) => res.json())
}
现在到了实际的错误:
let routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full'},
{ path: 'home', loadChildren: './home/home.module#HomeModule' }
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ]
})
export class AppModule {
constructor(private router:Router, private routerService:RouterService) {
// This works
// Pushing the same route as in routes.json
// ----------------------
routes.push({ path: 'contact', loadChildren: './contact/contact.module#ContactModule' })
router.resetConfig(router);
// This does not work
// Loads json data from service and push the new route
// ----------------------
this.routerService.getRoutes().subscribe((result) => {
result.forEach((route) => {
routes.push({ path: route.path, loadChildren: route.loadChildren })
});
this.router.resetConfig(routes);
});
// This does works
// By just console log this anonymous object, the loaded routing from the
// json data will work.
// ----------------------
console.log({ loadChildren: './contact/contact.module#ContactModule' })
this.routerService.getRoutes().subscribe((result) => {
result.forEach((route) => {
routes.push({ path: route.path, loadChildren: route.loadChildren })
});
this.router.resetConfig(routes);
});
}
这是经过测试的 Windows 7的, Angular-CLI(1.0.0-beta.21& 1.0.0-beta.26) 节点5.8.0
问题是,我是地球上第一个从REST服务添加路由还是让某人为此做出解决方法的人?