角路由器:如何替换参数? [英] Angular router: how to replace param?
问题描述
让我们假设我有3个网址:
/:projectId/info
,
/:projectId/users
,
/:projectId/users/:userId/profile
.它们都具有参数projectId
. UI具有从一个项目切换到另一个项目的组件.所以我需要:
Let's suppose I've got 3 urls:
/:projectId/info
,
/:projectId/users
,
/:projectId/users/:userId/profile
. All of them have param projectId
. UI has a component to switch from one project to another. So I need:
- 获取当前网址
- 按名称更改参数(例如projectId)
- 导航到新网址
所以我需要类似this.router.replaceParam(currentUrl, {projectId: 'project_id_2'})
的东西,它将把/project_id_1/users/user_id_1/profile
转换为/project_id_2/users/user_id_1/profile
(以及带有:projectId
参数的任何其他URL)
So I need something like this.router.replaceParam(currentUrl, {projectId: 'project_id_2'})
which will transform /project_id_1/users/user_id_1/profile
into /project_id_2/users/user_id_1/profile
(and any other URL with :projectId
param)
我认为这是一个简单而常见的问题,但是在1小时内没有找到解决方案.建议的此处解决方案如上一条评论中所述
I thought it's a simple and common problem but didn't find a solution in 1 hour. Suggested here solution doesn't work as noted in the last comment
推荐答案
要从当前网址导航到特定链接,您可以执行以下操作,
To navigate to particular link from current url, you can do something like this,
constructor(private route: ActivatedRoute, private router: Router){}
ngOnInit() {
this.route.params.subscribe(params => {
// PARAMS CHANGED ..
let id = params['projectid'];
});
}
navigate(){
this.router.navigateByUrl(this.router.url.replace(id, newProjectId));
// replace parameter of navigateByUrl function to your required url
}
在ngOnInit函数上,我们已经订阅了params,因此我们可以观察和执行url参数上的任何更改的语句.
On ngOnInit function, we have subscribed to params so we can observe and executes our statements on any change in url parameter.
这篇关于角路由器:如何替换参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!