简体   繁体   中英

How to protect route in angular4

I have Login/Create Account in My application. I want the user will not be able to see login/create account if user is already logged in. I am using an Authguard to protect the route:

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {debugger;
        if (localStorage.getItem('UserLoggedIn')) {
            // logged in so return true
            this.router.navigate(['']);
            return true;
        }

        // not logged in so redirect to login page with the return url
         this.router.navigate(['login']);
         return false;
    }

In this case the page is going in infinite loop.

This is my Routes:

const appRoutes: Routes = [
  { path: '', component: HomeComponent , data: { animation: '' }},
  { path: 'login', component: UserloginComponent , data: { animation: 'login' },canActivate:[AuthGuard]},
  { path: 'create-account', component: CreateAccountComponent, data: { animation: 'create-account' } },
  { path: 'forgot-password', component: ForgotPasswordComponent, data: { animation: 'forgot-password' } },
  { path: '**', component: PageNotfoundComponent }
];

Please Help. I want it for login and create account.

It is because you added this.router.navigate(['login']); to your authguard and this authguard was attached to login route. Each time a route was accessed it always call all the guards that was attached. So in your case if you access login, it will infinitely redirect to login. There are many ways to solve your issue. If you are intending to add the guard on the login route, just remove this.router.navigate(['login']); to avoid infinite loop. But i suggest to add the guard only to those routes you want to protect being accessed at if the user is not logged in.

Try this:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {debugger;

        let redirect: boolean = false;

        if (localStorage.getItem('UserLoggedIn')) {
            // logged in so return true
            this.router.navigate(['']);
            redirect = true;
        } else {
            // not logged in so redirect to login page with the return url
            this.router.navigate(['login']);
            redirect =  false;
        }


        return redirect;

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM