为什么在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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...