【问题标题】:Router Link rewrite url params路由器链接重写 url 参数
【发布时间】:2019-01-27 12:03:30
【问题描述】:

我的应用程序从以下路径 http://example.com/start 开始,在我使用 [routerLink] 之后,我希望开始的子字符串将被覆盖。

我尝试在 Angular 中更改路由,并在 Internet 上进行搜索,但没有找到任何解决方案。如果我点击链接,那么我的路径将如下所示http://example.com/start/newStart/123

<a [routerLink]="['/newStart', id]></a>

我的路由如下所示:

const routes: Routes = [
  { path: '', redirectTo: '/start', pathMatch: 'full' },
  { path: 'star', component: StartComponent },
  { path: ':id/:id', component: NewComponent },
  { path: '**', component: StartComponent }
];

我想要的是如果我点击链接来自的 URL 路径

http://example.com/start

应该是

http://example.com/newStart/123

解决方案

这对我有用。我只是在 newStart 之前添加斜线。

 <a [routerLink]="['/newStart', id]">

【问题讨论】:

  • 试试:&lt;a [routerLink]="['/newStart/'+id]&gt;&lt;/a&gt;

标签: angular routing


【解决方案1】:

这是stackblitz demo

使用以下链接:

<a [routerLink]="['start']">Start</a>
<a [routerLink]="['newStart', 123]">New start</a>

以及以下路由定义:

const routes: Routes = [
  { path: '', redirectTo: 'start', pathMatch: 'full' },
  { path: 'start', component: StartComponent },
  { path: 'newStart/:id', component: NewComponent },
  { path: '**', redirectTo: 'start' }
];

有两个组件StartComponentNewComponent, angular 会将您重定向到加载时的StartComponent (example.com -> example.com/start)。

当您单击newStart 链接时,url 将变为example.com/newStart/123,并且路由器将使用路由参数id = 123 加载NewComponent

【讨论】:

  • 很奇怪。它甚至无法在我的机器上运行。我第一次运行我的应用程序,路径是 localhost:4200/start,然后如果我点击链接,我会像你一样调整我的路线,但不起作用。我正在获取 localhost:4200/start/newstart。如果我将鼠标悬停在链接上,我也有 localhost:4200/start/newstart
  • 您能否提供代码的 Stackblitz 或最小复制?
  • 您好,请查看上方。我找到了解决办法。
猜你喜欢
  • 2018-04-30
  • 1970-01-01
  • 2018-02-04
  • 2019-02-24
  • 2020-07-20
  • 2012-04-06
  • 2020-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多