typescript - Angular 5 - Dynamisk rutt tillagd men inte routar
Jag har skapat ett nytt projekt och lagt till lite kod i routningsmodulen för dynamisk routning:
Här är koden för routningsmodulen:
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)}`);
});
}
}
och exempel länkarna på app.component.html
<a routerLink="home">Home</a>
<a routerLink="new/random/path">Dynamic</a>
<router-outlet></router-outlet>
Problemet är att även om den nya rutten har lyckats lagts till i routes-arrayen, får jag detta fel:
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'
Hur kan jag fixa detta?
Svar #1
Prova något som:
constructor(router: Router) {
const config = router.config;
config.push({path: 'new/random/path', component: OneComponent});
router.resetConfig(config);
}
