1
我想在運行時添加一些配置到Angular2路由器。Angular2路由器 - 無法使resetConfig工作
我在做什麼很簡單。在中的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);
}
}
當我現在嘗試導航與我排到PageNotFoundComponent代碼this.router.navigate(['/payment']);
到功能1。
相反,如果我在AppModule的配置中將路徑的配置配置爲function1,則一切正常。
我也在使用Angular-CLI。
任何幫助,非常感謝。在此先感謝
它的工作原理。謝謝。我不清楚我的原始解決方案有什麼不同。是r在Routes數組中的位置的問題?那個resetConfig是否需要一個新的數組才能真正改變?無論如何,謝謝 – Picci
resetConfig(config:Routes):void(來自[Router docs](https://angular.io/docs/ts/latest/api/router/index/Router-class.html)&[Routes文檔](https://angular.io/docs/ts/latest/api/router/index/Routes-type-alias.html))。 So Routes是一個接口Routes(一組路由配置),而不是一個簡單的Array。 「...」是一個Typescript Spread Operator [鏈接](https://basarat.gitbooks.io/typescript/content/docs/spread-operator.html) –
好的,我明白了。我沒有將我的對象投射到路線。這是問題所在。謝謝 – Picci