I am learning angular 13 & i am stuck at point, below is the code
this is my authservice file
export class AuthService {
loggedIn = false;
isAuthenticated() {
const promise = new Promise(
(resolve, reject) => {
setTimeout(() => {
resolve(this.loggedIn);
}, 800);
}
);
return promise;
}
}
i am getting this error
this is my auth guard service file
import { Injectable } from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivate,
Router,
RouterStateSnapshot,
} from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.isAuthenticated()
.then(
(authenticated: boolean) => {
if (authenticated) {
return true;
} else {
this.router.navigate(['/']);
}
}
);
}
}
Can anybody help me??
CodePudding user response:
You forgot to return false
in your else
statement.
.
.
.
if (authenticated) {
return true;
} else {
this.router.navigate(['/']);
return false; // <- add this here
}
CodePudding user response:
This issue occured because there is no return in your 'else' part. Try the Below code.
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.isAuthenticated()
.then(
(authenticated: boolean) => {
if (authenticated) {
return true;
} else {
this.router.navigate(['/']);
return false;
}
}
);
}