I have a separate service file called auth.service.ts
file which have promise that returns the loggedIn
value as true or false.
I have used a canActivate
method in separate auth.service.ts
file which uses the promise and loggedIn
value using of type boolean. But, it displays error if I mention it as boolean and even not mentioning anything and also given as any.
auth-guard.service.ts
file:
import { Injectable } from "@angular/core";
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from "@angular/router";
import { Observable } from "rxjs";
import { AuthService } from "./auth.service";
@Injectable()
export class AuthGuard implements CanActivate {
constructor( private authService : AuthService , private router : Router){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree | any > {
return this.authService.isAuthenticated()
.then(
(authenticated: boolean) => {
if (authenticated) {
return true;
}
else {
this.router.navigate(['/']);
}
}
);
}
}
auth.service.ts
file:
export class AuthService {
loggedIn : boolean = false ;
isAuthenticated(){
const promise = new Promise(
(resolve,reject) => {
setTimeout(
() => {
resolve(this.loggedIn);
},800);
}
);
return promise;
}
login(){
this.loggedIn = true ;
}
logout(){
this.loggedIn = false ;
}
}
Error facing:
Error: src/app/auth-guard.service.ts:17:13 - error TS2345: Argument of type '(authenticated: boolean) => true | undefined' is not assignable to parameter of type '(value: unknown) => true | PromiseLike<true | undefined> | undefined'.
Types of parameters 'authenticated' and 'value' are incompatible.
Type 'unknown' is not assignable to type 'boolean'.
17 (authenticated: boolean) => {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error: src/app/auth-guard.service.ts:17:13 - error TS7030: Not all code paths return a value.
17 (authenticated: boolean) => {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
× Failed to compile.
CodePudding user response:
after this.router.navigate(['/']) you have to add return false;
CodePudding user response:
Add error handler inside then and return in else:
return this.authService.isAuthenticated()
.then(
(authenticated: boolean) => {
if (authenticated) {
return true;
}
else {
return this.router.navigate(['/']);
}
},
err=> this.router.navigate(['/']
);
}