Angular 4:路由到路由不工作

Angular 4: Routing to a route doesn't work

Angular4 中有一些路由的基本概念我不明白。

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 中有一个 link:

<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 (in 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 },
];

在您的相对路径 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 });
}

relativeTo 通过创建相对于您提供的任何条目的路径来工作,它不一定需要是当前路径。

原来我的 firebase 代码搞砸了 - 它试图在转到另一条路线之前重新加载页面。这样就报错了,因为之前路由传过来的一些参数丢失了。

export const routing = RouterModule.forRoot(APP_ROUTES, { enableTracing: true })

在 app.routing.ts 中对调试非常有用。