【发布时间】:2018-01-26 05:44:54
【问题描述】:
我正在尝试在我的 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 中键入新添加的路由来访问它后,新添加的路由对象从路由数组中消失了。因此我得到了那个错误。
下图是在我添加动态路由对象之前
这是在我添加路由对象之后
但是当我尝试通过在 URL 中访问 /module3 路由时,
它只是重新初始化路由对象数组,因此它不包含新添加的路由。
我的问题是如何将这个新添加的路由保留到初始路由对象数组。这样当我尝试通过 URL 访问它时它就会在那里。
我在以下 GitHub 存储库中为此场景添加了示例 Angular 项目。
https://github.com/mal90/ng-dynamic-route
如果有人能指出我正确的方向,我们将不胜感激!
【问题讨论】:
-
点击页面上的module3链接是否有效?
-
是的。它在动态添加后在页面上工作。
-
您找到解决方案了吗?
标签: javascript angular angular2-routing angular-routing angular-router