Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - How do I get navigated from url in canactivate gaurd

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.

like image 766
Kashyap Avatar asked Nov 09 '16 21:11

Kashyap


2 Answers

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;
    }
}
like image 124
Maniac Avatar answered Sep 28 '22 19:09

Maniac


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;
}
like image 43
Vinay Pandya Avatar answered Sep 28 '22 18:09

Vinay Pandya