我创建了一个新项目,并向路由模块添加了一些代码以实现动态路由:
这是路由模块代码:
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)}`);
});
}
}
以及 app.component.html 上的示例链接”
<a routerLink="home">Home</a>
<a routerLink="new/random/path">Dynamic</a>
<router-outlet></router-outlet>
问题是,虽然新路线已成功推送到路线数组,但我收到此错误:
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'
我该如何解决这个问题?
最佳答案
尝试如下:
constructor(router: Router) {
const config = router.config;
config.push({path: 'new/random/path', component: OneComponent});
router.resetConfig(config);
}
关于Angular 5 - 添加动态路由但不路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48350889/