简体   繁体   English

在angular中实现canActivate auth Guard

[英]implementing canActivate auth guard in angular

I have a service with this function that returns true or false on rather or not a token is valid 我有一个带有此函数的服务,该函数在令牌无效时返回true或false

loggedIn() {
return this.http.get('http://localhost:3000/users/validateToken')
  .map(res => res.json()).map(data => data.success);
}

I have a auth guard with can activate on protected routes that uses this. 我有一个可以在使用此功能的受保护路由上激活的身份验证防护。

  canActivate(){
    this.authService.loggedIn().subscribe(res => {
      if(res) {
        return true;
      }
      else {
        this.router.navigate(['/login'])
        return false;
      }
    })
  }

But i get this error. 但是我得到这个错误。

incorrectly implements interface 'CanActivate'. 错误地实现了接口“ CanActivate”。 Types of property 'canActivate' are incompatible. 属性“ canActivate”的类型不兼容。 Type '() => void' is not assignable to type '(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => boolean | 类型'()=> void'不能分配给类型'(route:ActivatedRouteSnapshot,state:RouterStateSnapshot)=>布尔值| Promise | 承诺| Obser...'. 观察者...'。 Type 'void' is not assignable to type 'boolean | 不能将类型“ void”分配给类型“ boolean | Promise | 承诺| Observable'. 可观察的”。

How can i implement what I'm trying to do here ? 我如何才能在这里实现我要执行的操作?

The canActivate function must return a boolean, a promise of a boolean, or an observable of a boolean. canActivate函数必须返回一个布尔值,一个布尔值的promise或一个可观察的布尔值。

In your case, you return nothing. 就您而言,您什么也不返回。 Probably because you ommited the return in your function. 可能是因为您忽略了函数的return

But it wouldn't work if you add it, because then, you would return a subscription, which isn't accepted by the signature. 但是,如果添加它将不起作用,因为那样的话,您将返回订阅,签名不接受该订阅。

What you could do is this : 您可以执行以下操作:

canActivate() {
  return this.authService.loggedIn().map(res => {
    if(!res) {
      this.router.navigate(['/login']);
    }
    return res;
  });
}

With this code, you comply with the signature, and keep your routing logic. 使用此代码,您可以遵守签名并保留路由逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM