Imagine having two components called A
and B
. When Component A navigates to /a?random=random
and B navigates to /b
, I need to include the authUser
query parameter before the navigation begins. This way, the final URLs should look like this: /a?random=random&authUser=1
and /b?authUser=1
respectively.
However, the issue arises when the URL for component A
ends up looking like /a?authUser=1
after adding the authUser
queryParam, instead of /a?random=random&authUser=1
.
You can check out the code in this StackBlitz link.
// App component
ngOnInit() {
this.router.events.subscribe((event) => {
if(event instanceof NavigationStart) {
if (!event.url.includes('authUser')) {
// remove queryParams
const url = event.url.split('?')[0];
if (url !== '/') {
// /a/etc => ['a','etc']
const newUrl = url.split('/').filter(_subUrl => _subUrl);
this.router.navigate(newUrl, { queryParams: { authUser: '1' }, queryParamsHandling: 'merge' });
}
}
}
})
}
navigateToA() {
this.router.navigate(['a'], { queryParams: { random: 'random' } });
}
navigateToB() {
this.router.navigate(['b']);
}
I prefer not to modify the navigate methods of component A
and B
because changing them in a real application would require making modifications to every navigate method, which is not considered good practice.