【问题标题】:Angular 4: Routing to a route doesn't workAngular 4:路由到路由不起作用
【发布时间】: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


【解决方案1】:

原来我的 firebase 代码搞砸了——它会在转到另一条路线之前尝试重新加载页面。这导致了一个错误,因为从之前的路由中传递过来的一些参数丢失了。

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

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

【讨论】:

    【解决方案2】:

    在您的相对路径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 通过创建相对于您提供的任何条目的路径来工作,它不一定是当前路径。

    【讨论】:

    • this.router.navigate(['../']) 不会抛出错误,但它会将我带到我的主页。 this.router.navigate(['../collections']) 不起作用,它会引发与上述相同的错误。然后我尝试了 ActivatedRoute: Imported it (import { ActivatedRoute } from '@angular/router';) 并将其放入构造函数中,但“relativeTo: route”引发语法错误:找不到名称“route”任何。虽然它在构造函数中正确编写:路由:ActivatedRoute。你有预感它为什么会这样吗?
    • 尝试将route 更改为this.route。我犯这个错误的次数比我愿意承认的要多。
    • 这可能很尴尬,但我不知道我在做什么错误的语法。一定是小事,但我没看到。由于它与原始问题无关,我认为最好将其发布在 pastebin 上:pastebin.com/CY3M2Gvk。你能发现那里有什么明显的错误吗?
    • 我看不出你有什么问题,使用 this.router.navigate(['/collections']);应该也能正常工作。也许还有别的东西..但我看不出你所拥有的有什么问题。对不起,我不能再帮忙了:(
    • 我错过了构造函数中的“public”。但是 relativeTo 仍然没有解决问题。不过感谢您的帮助。
    猜你喜欢
    • 2018-06-17
    • 1970-01-01
    • 2017-08-20
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2014-05-05
    • 2017-11-04
    相关资源
    最近更新 更多