本文介绍了更新Angular 5中的routeparams的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条类似 dashboard/tour/2/269 的路线,此组件表示游览详细信息,并且在该组件内部有一些链接引用了相似的游览,因此,当用户单击一个链接时,在这些链接中,我想基于新参数重新加载组件,比如说 dashboard/tour/5/150 ,但是我尝试使用直接的 [routerLink] 它将新的参数附加到旧的参数上,变成这样的 dashboard/tour/2/269/tour/5/150 路线无效.

i have a route like this dashboard/tour/2/269, this component represents tour details, and inside that component there are some links which refer to similar tours, so when a user click one of those links i want to reload the component based on the new params like let's say this dashboard/tour/5/150, i tried to use a direct [routerLink] but it attach the new params to the old one to become like this dashboard/tour/2/269/tour/5/150 the route become invalid.

任何建议.

推荐答案

您将不得不将 ActivatedRoute 注入到您的组件中.您的路线必须这样设置:

You're going to have to inject ActivatedRoute into your component. Your routes would have to be set like this:

{ path: 'person/:id/:office_id', component: PersonComponent },

然后订阅参数:

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.params
    .subscribe(params => {
      const id = +params['id'];
      const office = +params['office_id'];
      console.log(`Current params are person ID ${id} and office ID ${office}`);
    });
}

您的routerLink为:

Your routerLink would be:

[routerLink]="['/persons', 2, 5]"

在这里,我在构造函数中将 ActivatedRoute 的实例作为 route 注入了.

Here, I have injected an instance of ActivatedRoute as route in my constructor.

您将需要获取Dashboard组件在路由中列出的每个参数.在此示例中,我的路由是简单的 persons/:id ,在这里我将从 http://localhost:3000/persons/1 获取 id >.因此,如果我有一个指向下一个人的路由器链接,说 [routerLink] ="['/persons',2]" ,此代码段将更新并为我提供一个 id 2 .

You would need to obtain each of you params that you have listed on your routing for your Dashboard component. In this example, my routing is simple persons/:id where I would get the id from http://localhost:3000/persons/1. So if I had a router link to next person say [routerLink]="['/persons', 2]", this snippet of code would update and provide me an id of 2.

根据您当前的插图和问题,这听起来像是您要寻找的解决方案.

Based on your current illustration and question, this sounds like the solution your looking for.

StackBlitz解决方案

https://stackblitz.com/edit/routing-params

这篇关于更新Angular 5中的routeparams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 14:05
查看更多