以角度 5 更新 routeparams [英] Update routeparams in angular 5
问题描述
我有一条这样的路线 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.
您需要获取您在仪表板组件的路由中列出的每个参数.在这个例子中,我的路由很简单 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
这篇关于以角度 5 更新 routeparams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!