【问题标题】:Angular 5 - Dynamic Route Added but not routingAngular 5 - 添加了动态路由但没有路由
【发布时间】:2018-06-29 06:32:22
【问题描述】:

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

这里是路由模块代码:

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'

我该如何解决这个问题?

【问题讨论】:

  • 我也想做同样的事情,你能分享你在这里实现的想法吗?我可以看到您已将 OneComponent 映射到所有动态路径。你是如何在单个组件中管理这么多代码的,或者你正在从那里做其他事情

标签: angular typescript angular-routing angular5


【解决方案1】:

尝试类似:

  constructor(router: Router) {
    const config = router.config;
    config.push({path: 'new/random/path', component: OneComponent});
    router.resetConfig(config);
  }

【讨论】:

  • 推送未添加到路由数组中
  • 我刚刚尝试了这段代码,它成功了。 github.com/garapa/studying/tree/master/dynamicRoutes 唯一忘了说的是需要将动态加载的组件添加到模块上的entryComponents数组中
  • @LeandroLima 你能分享相同的代码吗?谢谢
猜你喜欢
  • 2018-08-30
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
  • 2021-06-12
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 2018-11-11
相关资源
最近更新 更多