Angular routing with query parameters
Set queryParamsHandling: 'preserve'
in your navigation extras (Resource):
this.router.navigate(['/confirm'], { queryParamsHandling: 'preserve' });
Comments
-
phanf almost 2 years
I'm currently building on Angular: 7.2.14 and wanted to see if someone could explain how to redirect query parameters either with a route guard, shared service or other means etc.
The problem I'm trying to solve requires query parameters to come in from the root Uri path then redirect the route to the correct child component keeping the query intact when the router changes Uris.
For example, say you had an outside href linked into an angular app (see routes below) and the original route href is:
domain.com?foo=bar
, since this is the root route of''
angular will then transfer the route over to the matching child route''
this in turn redirects to'login'
. The end result lands you heredomain.com/#/login
and my query of?foo=bar
is lost.How do you create a route, route-guard or even a service etc. and maintain the original query but also redirecting you to the final location of
domain.com/#/login?foo=bar
starting from the root path?const routes: Routes = [ { path: '', component: AuthorizeComponent, children: [ { path: '', redirectTo: 'login' }, { path: 'login', component: LoginComponent, canActivate: [LoginGuardService] }, { path: 'confirm', component: ConfirmComponent, canActivate: [ConfirmGuardService] }, { path: 'error', component: ErrorComponent }, ] }];
I will try to show my setup here. I do have a
LoginGuardService
which implementscanActivate
and within the canActivate function I can redirect keeping the query together by usingrouter.navigate(['/login'], { queryParams: route.queryParams })
, except this ONLY works when you link directly to the route likedomain.com/#/login?foo=bar
not to the root first.LoginGuardService
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { if (this.auth.isLoggedIn()) { this.router.navigate(['/confirm'], { queryParams: route.queryParams }); } else { return true; } }
ConfirmGuardService
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { if (!this.auth.isLoggedIn()) { this.router.navigate(['/login'], { queryParams: route.queryParams }); } else { return true; } }