实现canActivate auth guard in angular [英] implementing canActivate auth guard in angular

查看:144
本文介绍了实现canActivate auth guard in angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用此函数的服务,返回true或false而不是令牌有效

I have a service with this function that returns true or false on rather or not a token is valid

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

我有一个auth guard可以在使用它的受保护路由上激活。

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;
      }
    })
  }

但我收到此错误。


错误地实现了接口'CanActivate'。属性类型
'canActivate'不兼容。
类型'()=> void'不能赋值为'(route:ActivatedRouteSnapshot,state:RouterStateSnapshot)=> boolean |
承诺| ...安装前后。
类型'void'不能赋值为'boolean |承诺| Observable'。

incorrectly implements interface 'CanActivate'. Types of property 'canActivate' are incompatible. Type '() => void' is not assignable to type '(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => boolean | Promise | Obser...'. Type 'void' is not assignable to type 'boolean | Promise | Observable'.

我如何实现我在这里尝试做的事情?

How can i implement what I'm trying to do here ?

推荐答案

canActivate 函数必须返回布尔值,布尔值的承诺或布尔值的可观察值。

The canActivate function must return a boolean, a promise of a boolean, or an observable of a boolean.

在您的情况下,您什么都不返回。可能是因为你在函数中省略了 return

In your case, you return nothing. Probably because you ommited the return in your function.

但是如果你添加它就行不通,因为那样你就会返回一个签名不被接受的订阅。

But it wouldn't work if you add it, because then, you would return a subscription, which isn't accepted by the signature.

你可以这样做:

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.

这篇关于实现canActivate auth guard in angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆