use*_*061 9 typescript angular2-routing angular angular4-router
在Angular 4中有一些基本的路由概念,我不明白.
index.html:
<base href="/">
Run Code Online (Sandbox Code Playgroud)
文件结构:
- app
|- app.routings.ts
|- collections
|-- collection.component.ts
|-- collection.component.html
|-- collectioninfo.component.ts
|-- collectioninfo.component.html
|- shared
|-- header.component.html
|-- header.component.ts
Run Code Online (Sandbox Code Playgroud)
我的header.component.html中有一个链接:
<a class="nav-link" [routerLink]="['/collections']">
Collections
</a>
Run Code Online (Sandbox Code Playgroud)
如果我点击它我登陆localhost:4200 /集合.单击按钮时,将以编程方式更改URL(在collection.component.ts中):
this.router.navigate(['/collections/', collection.name]);
Run Code Online (Sandbox Code Playgroud)
我最终在localhost:4200/collections/name - 一切都很好.现在我以编程方式想要回到/ collections(在collectioninfo.component.ts中):
this.router.navigate(['/collections']);
Run Code Online (Sandbox Code Playgroud)
但这不起作用.该网址没有更改,我收到一条错误消息,指出无法加载参数 - 显然/ collections/name正在再次加载.认为它可能是一个路径问题,但这样的事情也行不通:
this.router.navigate(['../collections']);
Run Code Online (Sandbox Code Playgroud)
附加信息:当我在打开/集合时手动重新加载页面时,我将再次转发到主页,但我认为这是另一个问题,与此行为无关.
app.routing.ts:
const APP_ROUTES: Routes = [
...
{ path: 'collections', component: CollectionComponent },
{ path: 'collections/:id', component: CollectionInfo },
];
Run Code Online (Sandbox Code Playgroud)
原来我的 firebase 代码搞砸了 - 它试图在转到另一条路线之前重新加载页面。这导致了错误,因为从之前的路由中传递过来的一些参数丢失了。
export const routing = RouterModule.forRoot(APP_ROUTES, { enableTracing: true })
Run Code Online (Sandbox Code Playgroud)
在 app.routing.ts 中对调试非常有用。
在您this.router.navigate(['../collections']);尝试导航到的相对路径中localhost:4200/collections/collections。尝试this.router.navigate(['../']);
如果这不起作用,还可以提供 ActivatedRoute 作为 relativeTo 参数:
constructor(route: ActivatedRoute, router: Router) {}
navigate() {
this.router.navigate(['../'], { relativeTo: this.route });
}
Run Code Online (Sandbox Code Playgroud)
relativeTo 通过创建相对于您提供的任何条目的路径来工作,它不一定需要是当前路线。
| 归档时间: |
|
| 查看次数: |
8596 次 |
| 最近记录: |