我想在angular 4应用程序中实现动态路由。我想要做的是将新的Route对象推送到Router config。代码看起来像
@
NgModule({
declarations: [
AppViewComponent
],
imports: [
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'appview', component: AppViewComponent }
{ path: '**', redirectTo: 'home' }
])
],
providers: []})
export class AppModuleShared {
constructor(router: Router, routerModule: RouterModule) {
console.log('Routes: ', JSON.stringify(router.config, undefined, 1));
router.config.push({ path: 'new/random/path', component: AppViewComponent });
router.config.forEach((x, i) => {
console.log(`${i}: ${JSON.stringify(x, undefined, 1)}`);
});
}}
当应用程序启动时,我想将新的Route Object推送到配置并转到构造函数中的新路径。执行构造函数后,在控制台日志中我有这样的东西:
5: {
"path": "new/random/path"
}
看起来新路由对象已成功推送到配置数组,但当我尝试进入此新路径时,应用程序会将我重定向到主页。你能否告诉我我做错了什么?
答案 0 :(得分:3)
使用unshift而不是push
实施例: router.config.unshift({path:'new / random / path',component:AppViewComponent});