Issue
I am trying to add some configuration to Angular2 Router
at runtime.
What I am doing is very simple. In the AppModule
I load the initial configuration of the Router
as per guidelines:
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);
Then in the AppComponent
onInit()
method I add some routes like this
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);
}
}
When I now try to navigate to function1 with the code this.router.navigate(['/payment']);
I am routed to the PageNotFoundComponent
.
On the contrary, if I put the configuration of the path to function1
in the configuration of AppModule
, everything works.
I am also using Angular-CLI.
Any help is very much appreciated. Thanks in advance
Solution
Try this code:
let r: Route = {
path: 'pop',
component: PopupComponent
};
this.router.resetConfig([r, ...this.router.config]);