Issue
in my Angular 12 project I have routes like these:
/:par1/:par2/something/page
/:par1/:par2/something2/page2
I need to set par1 and par2 programmatically.
Right now I use this code to achieve that:
const url = this.router.routerState.snapshot.url;
const splittedUrl = url.split('/');
splittedUrl[1] = getPar1();
splittedUrl[2] = getPar2();
this.router.navigate(splittedUrl);
but I find it a really ugly solution.
Is there a way to set par1 and par2 by their name like we do when we get them from the activated route?
Solution
I solved today the same problem.
This is my approach:
import ActivatedRoute into the constructor
constructor(private activatedRoute: ActivatedRoute)
use activatedRoute for getting the urlSegment and map an array with all segments (apply your change where needed)
This is an example applied at your problem
const url: string[] = this.activatedRoute.snapshot['_urlSegment'].segments.map((urlSegment: UrlSegment, index: number) => {
if (index === 0) return getPar1();
else if (index === 1) return getPar2();
else return urlSegment.path;
});
this.router.navigate(url);
Answered By - Kemot 90
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.