[英]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.