简体   繁体   中英

when i am using canActivate Guard it's leading to a blank page in angular 4?

I am trying to implement login functionality with angular 4 but when I am using canActivate Guard its leading me to a blank page,please help me

This is My loginservice

 isAuthenticated(){
   return localStorage.getItem('token') != null ;
   }

This is canActivate guard

  canActivate(route : ActivatedRouteSnapshot , state : RouterStateSnapshot){

    return this.loginservice.isAuthenticated();
  }

This is Router Module

 const appRoutes: Routes = [
  {path : '' , redirectTo:'/login', pathMatch :'full' },
  {path : 'login' , component : LoginComponent },
  {path : 'home' , component : HomeComponent, canActivate : [AuthGuard] ,children :[

          {path : 'adduser' , component : AdduserComponent },
          ]  

Your AuthGuard should redirect you to a default page if you are not authenticated or unauthorized.

constructor( private loginservice: LoginService, private router: Router) {

    }
public canActivate(route : ActivatedRouteSnapshot , state : RouterStateSnapshot){

    if(!this.loginservice.isAuthenticated()) {
            this.router.navigate(['login']); // choose either default route like here
            return false;
        }
    return true;
  }

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