【问题标题】:Property 'canActivate' in type 'AuthGuardService' is not assignable to the same property in base type 'CanActivate'“AuthGuardService”类型中的属性“canActivate”不可分配给基类型“CanActivate”中的相同属性
【发布时间】:2020-11-22 13:08:52
【问题描述】:

“AuthGuardService”类型中的属性“canActivate”不能分配给基类型“CanActivate”中的相同属性

export class AuthGuardService implements CanActivate {
  constructor(public authService: AuthService, public router: Router) {}
  async canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ):
    Promise<boolean | UrlTree | Observable<boolean | UrlTree>> {
    if (!await this.authService.chechAuthenticated()) {
      this.router.navigate(['login']);
      return false;
    }
    return true;
  }
}

给出错误:

“AuthGuardService”类型中的属性“canActivate”不能分配给基类型“CanActivate”中的相同属性。

【问题讨论】:

标签: angular async-await


【解决方案1】:

您不能使用异步更改签名,而是可以编写一个等待结果并返回 true 或 false 的函数,然后您可以从 canactivate 调用此函数。

export class AuthGuardService implements CanActivate {
   constructor(public authService: AuthService, public router: Router) {}
   canActivate(
       route: ActivatedRouteSnapshot,
       state: RouterStateSnapshot
   ){
        if(!isAuthenticated())
           this.router.navigate(['login']);
           return false;
        }
        return true;
   }
   async isAuthenticated() : bool {
      return Promise<boolean | UrlTree | Observable<boolean | UrlTree>> {
           return await this.authService.chechAuthenticated();
      }
   }

}

你可以这样做,请注意以上代码仅供参考,未经测试,可能包含编译问题。

【讨论】:

    【解决方案2】:
    export class AuthGuardService implements CanActivate {
      constructor(public authService: AuthService, public router: Router) {}
      async canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
      ): Promise<boolean | UrlTree> {
        let result = await this.authService.chechAuthenticated();
        if (!result) {
          return false;
        }
        return true;
      }
    }
    

    这样我的 AuthGuardServie 工作了。

    【讨论】:

      猜你喜欢
      • 2018-08-25
      • 2021-10-28
      • 2021-06-22
      • 1970-01-01
      • 2021-12-12
      • 2019-09-09
      • 2023-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多