I am using canActivate using guards in Angular. I want to check if the user is authenticated and based on the result protect the route.
There are two types of users: Type1 and Type2, so user can be either authenticated with Type1, Type2 or unauthenticated.
The following guard is for Type1 user.
Here is my code:
constructor(private authservice: AuthService, private router: Router, private route: ActivatedRoute){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{
const self = this;
const expectedType = "type1";
this.authservice.isUserAuthenticatedbyType(expectedType).then(
function(data){
if(data === false){
console.log(data);
self.router.navigate(['/'], {relativeTo: self.route});
}
return data;
},
function(error){
self.router.navigate(['/']);
return false;
}
);
return false;
}
The problem is I make an API call to validate if the user is authenticated and return false; is executed before the result from the API. So, momentarily I see a different page and then it is routed to the correct page. How can I fix this, I do not want to return false or true before the API call, but not doing that gives an error.
I also tried the following:
return this.authservice.isUserAuthenticatedbyType(expectedType)
But this simply navigates me to the http://localhost:4200 url in case of unauthenticated user.
I have the following route:
{ path: "", component: HomeComponent },
So, in the above scenario, HomeComponent should have been called, but ngOnInit of HomeComponent is not getting called.