javascript - 尝试通过 URL 访问时,Angular 2 动态路由不起作用

标签 javascript angular angular2-routing angular-routing angular-router

我正在尝试在我的 Angular 应用程序中存档动态路由。到目前为止我已经完成了以下功能。

  • 通过用户输入将路由添加到现有 Angular 组件。
  • 从现有的 Angular 应用程序中删除路由。

我使用router.resetConfig来执行此操作。

我的问题是,无论我添加什么新的动态路由,都无法通过输入 URL 来访问。它给了我以下错误。

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'module3'
Error: Cannot match any routes. URL Segment: 'module3'

这是我的代码

app.module.ts

const routes: Routes = [
  {
    path: '',
    component: Module1Component
  },
  {
    path: 'module2',
    component: Module2Component
  }
];

app.component.html

<div>
  <h2><a routerLink="">Module1</a></h2>
  <h2><a routerLink="module2">Module2</a></h2>
  <h2><a routerLink="module3">Module3</a></h2>
  <input type="button" value="add module 3 to route" (click)="addRoute()"/>
  <input type="button" value="remove module 3 from route" (click)="removeRoute()"/>
</div>

<router-outlet></router-outlet>

app.component.ts

addRoute(){
    let r: Route = {
      path: 'module3',
      component: Module3Component
    };
    this.router.resetConfig([r, ...this.router.config]);
    console.log(this.router.config);
  }

我发现,在尝试通过在浏览器 URL 中键入来访问新添加的路由后,新添加的路由对象会从路由数组中消失。因此我收到了这个错误。

下图是我添加动态路由对象之前

enter image description here

这是我添加路由对象之后的

enter image description here

但是当我尝试通过在 URL 中访问 /module3 路由时, 它只是重新初始化路由对象数组,因此它不包含新添加的路由。

我的问题是如何将这个新添加的路由保留到初始路由对象数组中。这样当我尝试通过 URL 访问它时它就会在那里。

我已在以下 GitHub 存储库中添加了针对此场景的示例 Angular 项目。

https://github.com/mal90/ng-dynamic-route

如果有人能指出我正确的方向,我将不胜感激!

最佳答案

Angular 是一个客户端框架,因此当您动态添加新路由时,只有当您不尝试通过服务器请求访问页面时,它才有效(当您在浏览器中输入 URL 时就是这种情况)

关于javascript - 尝试通过 URL 访问时,Angular 2 动态路由不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48456321/

相关文章:

javascript - D3 - 使用字符串作为轴刻度

javascript - 将对象添加到 parse.com 查询中的数组

javascript - "function loadGal($) "中的 $ 代表什么对象?

excel - 在 Angular 8 应用程序中导出 Excel 文件时如何定义单元格文本对齐方式?

javascript - 无法在 routerOnActivate 上获取查询参数

JavaScript 非正则表达式替换

node.js - 显示从 Node (服务器)到 Angular 2的图像?

typescript - 如何在angular2路由器中更改页面标题

基于角色的Angular 4路由默认页面

Angular 2 : using gzip files in production