Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Router - not able to make resetConfig work

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

like image 376
Picci Avatar asked Oct 06 '16 11:10

Picci


1 Answers

Try this code:

let r: Route = {
    path: 'pop',
    component: PopupComponent
};

this.router.resetConfig([r, ...this.router.config]);
like image 94
Fabrizio De Bortoli Avatar answered Nov 04 '22 07:11

Fabrizio De Bortoli