Angular 5 - 添加动态路由但不路由

标签 angular typescript angular-routing angular5

我创建了一个新项目,并向路由模块添加了一些代码以实现动态路由:

这是路由模块代码:

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/

相关文章:

javascript - 使用 Angular 2 的 http.get() 从本地文件加载 json

Angular 7 导航正在相应地更改 URL 但不加载组件

javascript - 在子组件的 ngAfterViewInit() 中调用时,父组件的元素上的 getElementById 返回 null

go - Go的http服务器可以编译 typescript 吗?

Angular 7 - 对象的 Observables 数组的 Observable 数组

json - 导入json文件导致HttpClient解析错误

javascript - ng2-charts\ng2-charts.js 不导出 ChartsModule

javascript - typescript 创建一个类隐藏其他类并返回通用结果

angular - SVG 模式在 Safari 中不起作用

angular - 子路由重新加载而不从父路由获取数据