Reputation: 685
I want to implement a dynamic routing in my angular 4 application. What I trying to do is to push new Route object to Router config. The code looks like
@
NgModule({
declarations: [
AppViewComponent
],
imports: [
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'appview', component: AppViewComponent }
{ path: '**', redirectTo: 'home' }
])
],
providers: []})
export class AppModuleShared {
constructor(router: Router, routerModule: RouterModule) {
console.log('Routes: ', JSON.stringify(router.config, undefined, 1));
router.config.push({ path: 'new/random/path', component: AppViewComponent });
router.config.forEach((x, i) => {
console.log(`${i}: ${JSON.stringify(x, undefined, 1)}`);
});
}}
When the application starts, I want to push new Route Object to config and go to that new path in a constructor. After constructor was executed, in console log I have something like this:
5: {
"path": "new/random/path"
}
it looks like the new Route Object was pushed successfully to the config array, but when I trying to enter to this new path application redirect me to the homepage. Could you please describe to me what I am doing wrong?
Upvotes: 5
Views: 3913
Reputation: 31
Use unshift instead of push
Example: router.config.unshift({ path: 'new/random/path', component: AppViewComponent });
Upvotes: 3