This will take a url string and update all the parameters that are in the params object:
constructor(private route: ActivatedRoute, private router: Router){}
setRouteParams(url: string, route: ActivatedRoute, params: any): string {
for (const p in params) {
const old = route.snapshot.paramMap.get(p);
url = url.replace(`/${old}/`, `/${params[p]}/`);
}
return url;
}
It iterates over the properties of params
gets the current value of each property p
from the current route then replaces it with the value of the property params[p]
. We want to know the current route param value so we know what needs replacing. Matching /${old}/
instead of old
will avoid situations like wanting to replace /aa/
with /bb/
in /aad/aa/
but getting /bbd/aa/
instead.
It can be called like this setRouteParams('/project_id_1/users/user_id_1/profile', this.activatedRoute, {projectId: 'project_id_2')
.
This will not handle routes like /11/users/11/profile/
with params
{userId: '22'}
. It will replace the projectId
instead. To handle that situation we need to know the order of the params {userId: {value: '22', position: 3}}
(1 based position because the first segment below will be the empty string).
setRouteParams(url: string, params: any): string {
const segments = url.split('/');
for (const p in params) {
segments[params[p].position] = params[p].value;
}
return segments.join('/');
}
If you want to navigate at the same time:
setRouteParamsAndNavigate(router: Router, params: any): void {
const segments = router.url.split('/');
for (const p in params) {
segments[params[p].position] = params[p].value;
}
router.navigateByUrl(segments.join('/')).then(() => {});
}