首页 文章

Angular2路由器 - 无法使resetConfig工作

提问于
浏览
3

我试图在运行时向Angular2路由器添加一些配置 .

我正在做的很简单 . 在AppModule中,我按照指南加载路由器的初始配置

AppModule

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    BrowserModule,
    routing,  
    ...
  ],
  providers: [appRoutingProviders],
  bootstrap: [AppComponent]
})
export class AppModule { }

appRoutes -- app.routes.ts

const appRoutes: Routes = [
        { path: '', component: PocWelcomeComponent },
        { path: '**', component: PageNotFoundComponent }
    ];

    export const appRoutingProviders: any[] = [

    ];

    export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

然后在AppComponent onInit()方法中添加一些这样的路由

AppComponent

export class AppComponent implements OnInit {

  constructor(
    private router: Router
  ) {}

  ngOnInit() {
    let routes = this.router.config;
    routes.push({ path: 'function1', component: Function1Component });
    this.router.resetConfig(routes);
  }

}

当我现在尝试使用代码 this.router.navigate(['/payment']); 导航到function1时,我将路由到PageNotFoundComponent .

相反,如果我在AppModule的配置中将路径的配置放到function1,一切正常 .

我也在使用Angular-CLI .

很感谢任何形式的帮助 . 提前致谢

1 回答

  • 6

    试试这段代码:

    let r: Route = {
        path: 'pop',
        component: PopupComponent
    };
    
    this.router.resetConfig([r, ...this.router.config]);
    

相关问题