Async authguard in angular 6

前端 未结 2 636
感情败类
感情败类 2021-01-03 02:42

I would like to provide a server-side authentication before I give access to a specific route in angular.

I have a AuthGuard which implements CanActivate and a servi

2条回答
  •  孤独总比滥情好
    2021-01-03 03:30

    You might do bit of changes as follows,

    Your service,

    @Injectable()
    export class LoginService {
      public isUserLoggedIn: boolean;
      constructor(
        private router: Router,
        private auth: AuthService) {
        this.isUserLoggedIn = false;
      }
    
      public loginService(data): void {
        this.auth.isAuthentication(data)
        .subscribe((response) => {
          if (response) {
            this.isUserLoggedIn = true;             
          }else {
            this.router.navigate(['login']);
          }
        });
      }
    
     public getUserLoggedIn() {
       return this.isUserLoggedIn;
    }
    

    and then,

    @Injectable()
    export class AuthGuard implements CanActivate {
      constructor(private login: LoginService) { }
      canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable | Promise | boolean {
        return this.login.getUserLoggedIn();
      }
    }
    

提交回复
热议问题