问题描述
假设我有 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
推荐答案
要从当前 url 导航到特定链接,您可以执行以下操作,
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.
编辑
案例:id 可以相同
constructor(private route: ActivatedRoute, private router: Router){}
projectId:string;
userId: string;
ngOnInit() {
this.route.params.subscribe(params => {
this.projectId = params['projectid'];
this.userId = params['userId'];
});
}
navigate(){
// for /project/:projectId/users/:userId/profile
this.router.navigate(['/project', this.projectId, '/users',
this.userId, '/profile']);
}
这篇关于角度路由器:如何替换参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!