为什么在AuthGuard中可观察到的始终为假?

问题描述

@Injectable()

export class AuthGuard implements CanActivate {

    constructor(private authService: AuthService,private router: Router){}

    canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
        const isAuth = this.authService.checkAuth()
        if (!isAuth){
            this.router.navigate(['/login'])
        }
        return isAuth;
    }
}

我不明白我在哪里错了,但是如果我用console.log记录,则isAuth始终为假。

编辑

  checkAuth(){
return this.loggedIn.asObservable();

}

loginUser(email: string,password:string){
    const user: User = {email: email,password: password}
    this.http.post<{token: string}>('http://localhost:3000/api/auth/login',user).subscribe( result => {
    const token = result.token;
    this.token = token
    this.loggedIn.next(true)
    this.router.navigateByUrl('/admin')
    })
  }

这很好,但是,这似乎不是一个好习惯。.并且我试图编写更好的代码行。

    @Injectable()
export class AuthGuard implements CanActivate {
auth: Subscription;
isAuth: boolean;
    constructor(private authService: AuthService,state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
        this.auth = this.authService.checkAuth().subscribe(result=>{
            this.isAuth = result
        })
        if (!this.isAuth){
            this.router.navigate(['/login'])
        }
        return this.isAuth;
    }
}

解决方法

@ Kardon63是的,但是我认为调用的方法是getValue()而不是value

因此,您必须更改checkAuth方法并编写:

checkAuth(){
  return this.loggedIn.getValue();
}

查看此帖子:https://stackoverflow.com/a/37089997/6444705