角度 6 中的异步 authguard

tim*_*ani 5 angular angular6

在以 angular 访问特定路由之前,我想提供服务器端身份验证。

我有一个实现 CanActivate 的 AuthGuard 和一个服务 AuthService。authService 已经有一个private loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null); 视图订阅以了解用户是否登录。我真的不知道我的方法是否错误,但它似乎不起作用。

这是我在 auth.guard.ts 中的内容:

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean> {
    return this.authService.isAuthenticated().map((isLoggedIn) => {
        if (isLoggedIn) {
            return true;
        } else {
            this.router.navigate(['/login']);
            return false;
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

这是 auth.service.ts:

    @Injectable()
export class AuthService {
    private loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);

    constructor(
        private router: Router,
        private http: HttpClient
    ) {

    }

    get isLoggedIn() {
        return this.loggedIn.asObservable();
    }

    isAuthenticated() : Observable<boolean> {
        const headers = new HttpHeaders().set("X-Requested-With", "XMLHttpRequest");

        return this.http.get('/user', {headers: headers}).map(
            response => {
                if (response['username']) {
                    this.loggedIn.next(true);
                    return true;
                } else {
                    return false;
                }
            }
        )
    }
Run Code Online (Sandbox Code Playgroud)

Saj*_*ran 1

您可以进行如下一些更改,

您的服务,

@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;
}
Run Code Online (Sandbox Code Playgroud)

进而,

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