0
@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,private router: Router){}

    canActivate(route: ActivatedRouteSnapshot, 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;
    }
}
4

1 回答 1

1

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

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

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

检查这篇文章:https ://stackoverflow.com/a/37089997/6444705

于 2020-08-20T14:38:27.320 回答