1

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.

2
  • queryParamsHandling : 'preserve' Commented Jul 11, 2018 at 9:34
  • You can put condition in your guard itself check that if url has your query string and match with your desired values if not then redirect to sample page. Commented Jul 11, 2018 at 9:36

1 Answer 1

3

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));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.