Angular 4动态路由

Mat*_*usz 5 angular angular-router

我想在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)}`);
    });
}}
Run Code Online (Sandbox Code Playgroud)

当应用程序启动时,我想将新的Route Object推送到配置并转到构造函数中的新路径.执行构造函数后,在控制台日志中我有这样的事情:

5: {
    "path": "new/random/path"
}
Run Code Online (Sandbox Code Playgroud)

看起来新的Route Object被成功推送到配置数组,但是当我尝试进入这个新的路径时,应用程序将我重定向到主页.你能告诉我我做错了什么吗?

小智 3

使用unshift代替push

示例: router.config.unshift({ 路径: 'new/random/path', 组件: AppViewComponent });