Reputation:
I have created a new project and added some code to to the routing module for dynamic routing:
Here is the routing module code:
import { NgModule } from '@angular/core';
import { Routes, RouterModule, Router} from '@angular/router';
import { OneComponent } from './one/one.component';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
constructor(router: Router, routerModule: RouterModule) {
console.log('Routes: ', JSON.stringify(routes, undefined, 1));
routes.push({path: 'new/random/path', component: OneComponent});
routes.forEach((x, i) => {
console.log(`${i}: ${JSON.stringify(x, undefined, 1)}`);
});
}
}
and the example links on app.component.html"
<a routerLink="home">Home</a>
<a routerLink="new/random/path">Dynamic</a>
<router-outlet></router-outlet>
The problem is that although the new route has successfully been pushed to the routes array, I'm getting this error:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'new/random/path'
Error: Cannot match any routes. URL Segment: 'new/random/path'
How can I fix this?
Upvotes: 2
Views: 6341
Reputation: 1164
Try something like:
constructor(router: Router) {
const config = router.config;
config.push({path: 'new/random/path', component: OneComponent});
router.resetConfig(config);
}
Upvotes: 3