Angular 4: 路由到某个路径不起作用

10

我不理解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 吗?我不知道它是否能解决你的问题,但我在我的编程页面更改中使用它。 - Surreal
1
谢谢你的提示,不幸的是那也不行(某些行为)。 - user3255061
也许是语法问题?尝试去掉括号 this.router.navigateByUrl('/collections'); - Surreal
1
@Surreal:无论如何,它都可以正常工作,没有括号也没关系。但还是谢谢你的提示。 - user3255061
@Brandon:不好意思,那种方法不起作用。 - user3255061
显示剩余10条评论
2个回答

6
原来我的Firebase代码有问题——它在转到另一个路由之前尝试重新加载页面。这导致出现错误,因为缺少从上一个路由传递过来的某些参数。
export const routing = RouterModule.forRoot(APP_ROUTES, { enableTracing: true })

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


5
在您的相对路径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 });
}
< p > relativeTo 的工作原理是基于你提供的任何路径创建一个相对路径,而且它不一定需要是当前路由。 < /p >

this.router.navigate(['../'])不会出现错误,但会将我带到首页。然而,this.router.navigate(['../collections'])不起作用,会抛出与上述相同的错误。我随后尝试了ActivatedRoute: 导入它(import { ActivatedRoute } from '@angular/router';)并将其放入构造函数中,但是"relativeTo: route"会抛出语法错误:"route"未找到任何名称。尽管在构造函数中已正确写入:route: ActivatedRoute。您有什么直觉为什么它表现得像那样吗? - user3255061
尝试将 route 更改为 this.route。我犯这个错误的频率比我想承认的要多。 - tylerwgrass
这可能很尴尬,但我不知道我的语法错在哪里。一定是个小问题,但我没看出来。由于它与原始问题无关,我认为最好将其发布在pastebin上:https://pastebin.com/CY3M2Gvk。你能发现那里有任何明显的错误吗? - user3255061
我认为你的代码没有问题,使用 this.router.navigate(['/collections']); 也应该可以正常工作。可能还有其他问题,但是我没有发现你的代码有任何错误。很抱歉我无法提供更多帮助 :( - tylerwgrass
我在构造函数中漏掉了“public”。但是,relativeTo仍然没有解决问题。不过还是谢谢你的帮助。 - user3255061

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接