【发布时间】:2018-02-22 08:44:19
【问题描述】:
Angular 4 中有一些基本的路由概念我不明白。
index.html:
<base href="/">
文件结构:
- app
|- app.routings.ts
|- collections
|-- collection.component.ts
|-- collection.component.html
|-- collectioninfo.component.ts
|-- collectioninfo.component.html
|- shared
|-- header.component.html
|-- header.component.ts
我的 header.component.html 中有一个链接:
<a class="nav-link" [routerLink]="['/collections']">
Collections
</a>
如果我点击它,我会登陆 localhost:4200/collections。单击按钮时,会以编程方式更改 url(在 collection.component.ts 中):
this.router.navigate(['/collections/', collection.name]);
我最终访问了 localhost:4200/collections/name - 一切都很好。现在我想以编程方式返回 /collections(在 collectioninfo.component.ts 中):
this.router.navigate(['/collections']);
但这不起作用。 url 没有改变,我收到一个错误,说无法加载参数 - 所以显然 /collections/name 正在再次加载。认为这可能是路径问题,但这样的事情也不起作用:
this.router.navigate(['../collections']);
附加信息:当我在 /collections 上手动重新加载页面时,我再次被转发到主页,但我认为这是另一个问题,与此行为无关。
app.routing.ts:
const APP_ROUTES: Routes = [
...
{ path: 'collections', component: CollectionComponent },
{ path: 'collections/:id', component: CollectionInfo },
];
【问题讨论】:
-
您是否尝试过
navigateByUrl而不是navigate,我不知道它是否能解决您的问题,但我将它用于我的程序化页面更改 -
感谢您的提示,不幸的是,这也不起作用(某些行为)。
-
你的空路径是如何定义的,你的 header 中的 isAuthenticated 是什么?
-
翻转路线的顺序,首先制作最具体的路线。您收到有关缺少参数的错误的原因是因为
/collections正在落入CollectionsInfo路线。或者,使用完全匹配的路线。 -
@Surreal:无论如何,它只是在没有括号的情况下工作。不过谢谢你的提示。
标签: angular typescript angular2-routing angular4-router