Angular 5 - 添加了动态路由但未添加路由 [英] Angular 5 - Dynamic Route Added but not routing

查看:30
本文介绍了Angular 5 - 添加了动态路由但未添加路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a new project and added some code to to the routing module for dynamic routing:

这里是路由模块代码:

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 上的示例链接"

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?

推荐答案

尝试类似:

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

这篇关于Angular 5 - 添加了动态路由但未添加路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆