Im newbee for angular 7 and now trying to implement CanActive, but im getting error :
Can anyone guide me to overcome this. My code samples are as follows :
auth.guard.ts :
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth-service.service';
import {Router} from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService,
private myRoute: Router){
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (this.auth.isLoggednIn()){
return true;
} else {
this.myRoute.navigate(["login"]);
return false;
}
}
}
You are using a promise as an if
condition and the promise may throw an error.
So you could either simply wrap it with a try/catch block or you could wrap it within another promise instance and return the auth result by using resolve
to pass it further down the line:
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Promise<boolean> | boolean {
return new Promise(resolve =>
this.auth.isLoggednIn()
.then(status: boolean => {
if(status === false) {
this.myRoute.navigate(["login"]);
}
resolve(status);
})
.catch(() => {
this.myRoute.navigate(["login"]);
resolve(false);
// ... or any other way you want to handle such error case
})
}
}