Reputation: 2226
I have a protected route /protected-route
. The authentication-guard.service.ts
file dictates that a user must be thrown to /login
if a valid session is not found:
/* --- Angular --- */
import { Injectable } from '@angular/core';
import { CanActivate, Router, RouterStateSnapshot } from '@angular/router';
/* --- Services --- */
import { AuthenticationService } from './authentication.service';
import { StorageService } from './storage.service';
@Injectable()
export class AuthenticatedRouteGuardService implements CanActivate {
constructor(private authenticationService: AuthenticationService, private
router: Router, private routerStateSnapshot: RouterStateSnapshot) { }
canActivate() {
if (this.authenticationService.isAuthenticated()) { return true; } else {
console.log(this.routerStateSnapshot.url);
this.router.navigate(['/login']);
return false;
}
}
}
I would like to save the attempted route, i.e. /protected-route
to be able to redirect the user after successful login. I am unable to get the route information before the user gets thrown to /login
. router.url
and activatedRoute.snapshot.url
both return empty values.
Upvotes: 3
Views: 1269
Reputation: 146
Use this in your AuthenticatedRouteGuardService
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authenticationService.isAuthenticated()) {
return true;
}
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
Upvotes: 2