[英]Type 'boolean | undefined' is not assignable to type 'boolean'. Type 'undefined' is not assignable to type 'boolean'
Hello I'm workig in an angular project with php. But I have this error "Type 'boolean | undefined' is not assignable to type 'boolean'. Type 'undefined' is not assignable to type 'boolean'" in this line "return this.isLogin(routeurl);".你好,我在一个 angular 项目中工作,项目编号为 php。但是我有这个错误“Type 'boolean | undefined' is not assignable to type 'boolean'. Type 'undefined' is not assignable to type 'boolean'” 在这一行“返回 this.isLogin(routeurl);”。 How can I solve it please?
请问我该如何解决?
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, CanActivate, Router } from
'@angular/router';
import { ApiService } from './api.service';
@Injectable({
providedIn: 'root'
})
export class AuthguardGuard implements CanActivate {
constructor(private dataService: ApiService,private router: Router ) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
const routeurl: string = state.url;
return this.isLogin(routeurl);
}
isLogin(routeurl: string) {
if (this.dataService.isLoggedIn()) {
return true;
}
this.dataService.redirectUrl = routeurl;
this.router.navigate(['/login'], {queryParams: { returnUrl: routeurl }} );
}
}
I have also this error "(method) AuthguardGuard.isLogin(routeurl: string): true | undefined Not all code paths return a value."我也有这个错误“(方法)AuthguardGuard.isLogin(routeurl:string):true | undefined Not all code paths return a value.” in this line "isLogin(routeurl: string) " thanks in advance
在这一行“isLogin(routeurl:string)”提前致谢
Typescript complains that you return a value of type boolean | undefined
Typescript 抱怨你返回一个类型为
boolean | undefined
boolean | undefined
when it expects it to be just boolean
. boolean | undefined
当它期望它只是boolean
。
Assuming the return type of this.isLogin(routeurl)
is boolean | undefined
假设
this.isLogin(routeurl)
的返回类型是boolean | undefined
boolean | undefined
you could simply return a default value when it actually is ùndefined
. boolean | undefined
当它实际上是ùndefined
时,你可以简单地返回一个默认值。
return this.isLogin(routeurl) ?? false;
For your second problem you simply have to return something at the end of the method:对于你的第二个问题,你只需要在方法结束时返回一些东西:
isLogin(routeurl: string) {
if (this.dataService.isLoggedIn()) {
return true;
}
this.dataService.redirectUrl = routeurl;
this.router.navigate(['/login'], {queryParams: { returnUrl: routeurl }} );
return;
}
The undefined is diff from the boolean. If your function can return undefined you need to explicit this like: undefined 与 boolean 不同。如果您的 function 可以返回 undefined,您需要像这样显式:
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean | undefined {
const routeurl: string = state.url;
return this.isLogin(routeurl);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.