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);". 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." in this line "isLogin(routeurl: string) " thanks in advance
CodePudding user response:
Typescript complains that you return a value of type boolean | undefined
when it expects it to be just boolean
.
Assuming the return type of this.isLogin(routeurl)
is boolean | undefined
you could simply return a default value when it actually is ù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;
}
CodePudding user response:
The undefined is diff from the boolean. If your function can return undefined you need to explicit this like:
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean | undefined {
const routeurl: string = state.url;
return this.isLogin(routeurl);
}