简体   繁体   English

Angular Admin Guard 问题无法测试“void”类型的表达式的真实性

[英]Angular Admin Guard problem An expression of type 'void' cannot be tested for truthiness

I have我有

public getUser(userId: string) {
return this.http.get<{
  _id: string;
  registrationStep: number;
  userType: string;
  isAdmin: boolean;
}>(BACKEND_URL+"getUserData/" + userId);

} }

in my auth service.在我的身份验证服务中。 I want to read boolean value from database and set Admin guard to true.我想从数据库中读取 boolean 值并将 Admin guard 设置为 true。

I'm calling the function getIsAdmin from AdminGuard我从 AdminGuard 调用 function getIsAdmin

getIsAdmin() {
this.getUser(this.getUserId()).subscribe(result => {
  return result.isAdmin;
});

} }

And this is my Admin Guard code这是我的管理员守卫代码

    import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router
} from "@angular/router";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";

import { AuthService } from "./auth.service";

@Injectable()
export class AdminGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean | Observable<boolean> | Promise<boolean> {
    const isAdmin = this.authService.getIsAdmin();
    if (!isAdmin) {
      this.router.navigate(['auth/admin']);
    }
    return isAdmin;
  }
}

I get An expression of type 'void' cannot be tested for truthiness.我得到“无效”类型的表达式无法测试其真实性。 Thank you for your help!谢谢您的帮助!

As others are pointing out you DO NOT need to subscribe.正如其他人指出的那样,您不需要订阅。 canActivate accepts an Observable<boolean> as a return type. canActivate接受Observable<boolean>作为返回类型。

If you subscribe, the canActivate function will have already returned and you won't get the value of the subscription back.如果您订阅, canActivate function 将已经返回,您将无法取回订阅的值。

The following implementation should suffice:以下实现应该足够了:

// authService
getIsAdmin(): Observable<boolean> {
    return this.getUser(this.getUserId()).pipe(
        map(user => user.isAdmin)
    );
}

And for the canActivate you want to do a custom redirect upon receiving false so you could:对于canActivate ,您希望在收到false时进行自定义重定向,以便您可以:

canActivate(…): Observable<boolean> {
    const isAdmin$ = this.authService.getIsAdmin();
    return isAdmin$.pipe(
        tap(isAdmin => {
            if(!isAdmin) {
                this.router.navigate(['auth/admin']);
            }
        })
    );
}

return an observable from the method "getIsAdmin", then subscribe it in canActivate method and the assign the value to isAdmin variable从方法“getIsAdmin”返回一个 observable,然后在 canActivate 方法中订阅它并将值分配给 isAdmin 变量

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

相关问题 Typescript:检查变量的真实性不会对未定义进行类型防护吗? - Typescript: checking truthiness of variable doesn't type-guard against undefined? 角度错误:类型“void”不可分配给类型“AbstractControl” - Angular Error : Type 'void' is not assignable to type 'AbstractControl' Angular 7类型“ void”不可分配给类型“ ObservableInput &lt;{}&gt;” - Angular 7 Type 'void' is not assignable to type 'ObservableInput<{}>' 运算符 '&gt;' 不能应用于 Angular 8 中的类型 'void' 和 'number' - Operator '>' cannot be applied to types 'void' and 'number' in Angular 8 angular 括号的正则表达式问题 - Regular Expression problem with angular brackets 角度2中的类型&#39;void&#39;上不存在属性&#39;subscribe&#39; - Property 'subscribe' does not exist on type 'void' in angular 2 'void'类型上不存在属性'管道' Angular 9 - Property 'pipe' does not exist on type 'void' Angular 9 在 TypeScript 中使用 supertest - 遇到问题“无法调用类型缺少调用签名的表达式” - Using supertest in TypeScript - Getting problem "cannot invoke expression whose type lacks a call signature" Angular 5:类型&#39;void&#39;的参数不是赋值给&#39;{} |类型的参数 PromiseLike &lt;{}&gt;” - Angular 5: Argument of type 'void' is not assignment to parameter of type '{} | PromiseLike<{}>' 表达式类型“字符串”不能用作索引类型 - Expression Type 'String' cannot be used as an index type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM