【问题标题】:Angular : how to send params with routing path?Angular:如何使用路由路径发送参数?
【发布时间】:2018-01-24 12:44:37
【问题描述】:

假设我有三个描述类别(汽车、颜色、食品)的不同 API。在routerLink 我使用这个routerLink="/{{element.name}}" 在我的模块中我使用:

 path: ':id',
 component: ListComponent

现在,当我路由时,它变成了这样:localhost:4200/red,这对我来说很好,但是我怎样才能用这个 URL 发送一些独特的东西来确保元素是彩色的并在我的代码中的某个地方处理它呢?

【问题讨论】:

标签: angular routing


【解决方案1】:

使用这样的东西:

export const routes: Routes = [
  //...
  { path: 'colors/:color', component: ColorsComponent },
  //...
];

您可以在模板中像这样使用这些路由:

<a [routerLink]="['/colors', 'red']">Something</a>

或者:

goToRed() {
  this.router.navigate(['/colors', 'red']);
}

当然'red' 也可以是一个变量。 并且你可以在你组件的ngOnInit()订阅这个参数:

ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.color = params['color'];
       //You can check the color here.
    });
  }

您也可以将此方法用于汽车和食品。


更新:

如果您想传递额外的“参数”。你可以试试这个:

{
    path: 'colors/:color',
    component: ColorComponent,
    data: {someValue: 123}
}

在您的组件中,您可以使用this.route.data 来访问它。 URL 仍将如下所示:例如localhost:4200/colors/red。

【讨论】:

  • 完美!但是我怎样才能使我的网址像这样localhost:4200/red 但在我的函数中我想发送id 而不是名称,所以我需要向用户显示“红色”字但实际上值是id跨度>
  • 在我的代码中,URL 将如下所示(例如):localhost:4200/colors/red,并且 params['color'] 的值为 'red' 作为字符串。
  • 是否要向组件发送附加参数而不在 URL 中显示?
  • 是的,例如,如果我有 localhost:4200/red/123,我希望用户显示的 url 像这样 localhost:4200/red,但在我的函数中,我将忽略汽车并处理 id 123。
  • 很好,但是我在哪里可以将 123 从我的 html 传递到附加参数?
猜你喜欢
  • 2017-12-05
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 2021-04-15
  • 2020-08-30
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
相关资源
最近更新 更多