I have page1 and page2. I added canActivate gaurd on page2 route and want to know in the if I came from page1? How do I do that?
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
//If from Page 1 { clearCache() }
return true;
}
Thanks in advance.
I was trying to find the answer to this question as well, and finally found it. In the constructor for your guard class, you need (private router: Router); then in your canActivate guard, you can use this.router.url to check the URL you are coming from:
export class StatusGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
console.log(`route ${route.url}`); // the url you are going to
console.log(`state ${state.url}`); // the url you are going to
console.log(`router ${this.router.url}`); // the url you are coming from
return true;
}
}
First doit like this: it will give you a URL:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
console.log(state.url);
}
if you want to redirect user to from which url he/she came from you can do it like this: for information read official tutorial docs under TEACH AUTHGUARD TO AUTHENTICATE section.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
return this.checkLogin(url);
}
checkLogin(url: string): boolean {
if (this.authService.isLoggedIn) { return true; }
// Store the attempted URL for redirecting
this.authService.redirectUrl = url;
// Navigate to the login page with extras
this.router.navigate(['/login']);
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With