问题描述
我写下面的代码作为我的主页面防护,它使用 checkTokenValidation()
从用户获得有效的身份验证令牌,但我的IDE显示此错误:声明其类型既不是'void'也不是'any'的函数'必须返回一个值.我返回我的订阅布尔值,但我不知道为什么会有这个问题.我测试了我的代码,并了解我的代码没有执行返回行是true还是false,这很奇怪.
i write below code as my main page guard that use checkTokenValidation()
to valid authentication token from user but my IDE show this error :A function whose declared type is neither 'void' nor 'any' must return a value.i return in my subscribe boolean but i don't know why i have this problem. i test my code and understand my code does not execute my return line as true or false and it is strange.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
this.authService.checkTokenValidation().subscribe((data) => {
console.log(data);
if (data['ok']) {
this.router.navigate(['/overview']);
return false;
} else {
return true;
}
});
}
推荐答案
通过订阅,您返回的是 Subscription
而不是 Observable
.您应该映射到所需的值并返回 Observable
:
By subscribing you are returning a Subscription
instead of an Observable
.You should map to the desired values and return an Observable
:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.checkTokenValidation().pipe(
map( (data) => {
if (data['ok']) {
this.router.navigate(['/overview']);
return false;
} else {
return true;
}
})
);
}
这篇关于canActivated防护的返回值错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!