【问题标题】:Angular2 Router - not able to make resetConfig workAngular2路由器 - 无法使resetConfig工作
【发布时间】:2016-10-06 11:38:52
【问题描述】:

我正在尝试在运行时向 Angular2 Router 添加一些配置。

我所做的很简单。在AppModule 中,我按照指南加载Router 的初始配置:

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() 方法中添加一些这样的路由

应用组件

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

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

我也在使用 Angular-CLI。

非常感谢任何帮助。提前致谢

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    试试这个代码:

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

    【讨论】:

    • 它有效。谢谢。我不清楚与我原来的解决方案有什么不同。是 r 在 Routes 数组中的位置问题吗?那 resetConfig 是否需要一个新的 Array 才能实际更改?无论如何谢谢
    • resetConfig(config: Routes) : void(来自 Router docsRoutes docs )。所以Routes是一个接口Routes(路由配置的数组),而不是简单的Array。 "..." 是一个打字稿传播运算符link
    • 好的,我明白了。我没有将我的对象转换为路由。这就是问题所在。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多