【问题标题】:Change Id to Name in Angular 2 Route在 Angular 2 路由中将 ID 更改为名称
【发布时间】:2017-06-22 13:54:38
【问题描述】:

好吧,在问这个问题之前我做了一些研究。我认为这是非常简单的,因为这是常见的情况。

这是我的锚标记。

  <a [routerLink]="['./product', 1]">Vitamins</a>

当使用点击时,我通过将 Id 传递给 Web API 来获取数据。获取数据后,Url 显示为http://localhost:4200/product/1

在我的路线中,我将其配置为

{ path: 'product/:id', component: ProductComponent },

我想将此 URL 修改为 http://localhost:4200/vitamins,这样更有意义。我该怎么做?

我找到的最接近的是这个,但这不是我要找的

Angular 2 : routing without changing URL

【问题讨论】:

  • 只要名字是唯一的,就可以用名字作为id。
  • @RobinDijkhof 名字不是 unquie。即使它是独一无二的,我想我会得到它localhost:4200/product/Vitamins。但我不想要介于两者之间的产品。谢谢
  • 或者你可以做{ path: 'product/:productName/:id', component: ProductComponent }
  • 来自http://localhost:4200/vitamins 路由器如何知道您要将ProductComponent 加载到插座?您可以通过将名称映射到 id 来使用 product/:productName
  • 您可以将路径更改为{ path: 'vitamins', component: ProductComponent } &lt;a routerLink="'./vitamins'"&gt;Vitamins&lt;/a&gt; 注意删除的括号,否则您会在服务器端获得IllegalNumberException

标签: angular typescript angular2-routing


【解决方案1】:

尝试使用 Location 对象。

import { Location } from '@angular/common';

constructor(public location: Location) {}

当你想更新窗口 URL 而不用路由对象重定向或导航时,把这个:

this.location.go('vitamins');

这应该在你的基本网址之后写上“维生素”。

【讨论】:

  • 不确定这是否是一个好方法。我观察到 URL 首先显示为localhost:4200/product/1,然后更改为localhost:4200/vitamins。用户可以看到闪烁
  • 我观察到的另一件事是用户无法输入 Website.com/Vitamins
  • 您可以尝试在您的 ngOnInit 方法中使用它。否则,你什么时候必须切换网址? -- 编辑然后你应该用维生素实现一条新路线
【解决方案2】:

我可能只会链接到&lt;a [routerLink]="'/product'"&gt;Vitamins&lt;/a&gt;。 使其成为可选并在您的组件或服务中处理这种情况(如果没有传递id,请将其设置为1

在其他情况下,您可能希望 url 看起来像 http://myexample.com/vitamins/2,否则无法直接链接(否则您将如何传递参数?)例如,如果您不想为 url 添加书签或制作硬重新加载。

一个 hacky 方法是使用 location.go('/vitamins'); (Location Docs),它会更改地址栏中的 url,但不会触发 angular router 的任何路由更改。 我称它为 hacky,因为如果您在特定路线上,它可能会产生诸如书签/重新加载问题之类的副作用(当然您可以通过另一种方式解决这个问题,比如说暂时将当前路线参数保存在 localStorage 中)。

希望我能帮上忙。

【讨论】:

    猜你喜欢
    • 2018-09-09
    • 2016-09-08
    • 1970-01-01
    • 2011-09-29
    • 2020-04-26
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多