Reputation: 5204
I am writing my angular 5+ app and using AuthGuardService
what I am doing is that I am redirecting from another php
application which send me form data in query string
http://localhost:44200/#/users/save?first_name=John&last_name=Doe
the AuthGuardService
properly redirect user to login if he is not logged in with following code
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
if(localStorage.getItem('crmUser')){
return true;
}
this.router.navigate(['/login'], { queryParams: {returnUrl: state.url},queryParamsHandling: 'merge' });
return false;
}
But after login I can redirect to return url if it has no query string, I want to redirect user to same page with all query string.
Please guide me how to handle it.
Upvotes: 1
Views: 2974
Reputation: 4451
This is how I did it. In your AuthGuard#canActivate add the following:
@Injectable()
export class AuthGuard implements CanActivate{
originRoute:ActivatedRouteSnapshot;
constructor(private authentificationService: AuthChecker,
private router: Router){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if(localStorage.getItem('crmUser')){
return true;
}
this.originRoute = route;
this.router.navigate(['/login'], { queryParams: {returnUrl: state.url},queryParamsHandling: 'merge' });
return false;
}
}
public hasOriginRoute(): boolean{
return this.originRoute != null;
}
}
Now in your LoginComponent when login succeeded add:
if(this.authGuard.hasOriginRoute()){
this.router.navigate(this.authGuard.originRoute.url.map((x) => x.path));
}
Upvotes: 3