I am making an Angular 4 web app. I need to protect my routes so I am using AuthGuard
and CanActivate
to check if the user can access a certain route.
CanActivate
first checks if the id
is in sessionStorage
else it checks my backend if the user is authorized. If I click on a project with an id
already in sessionStorage
and it goes into the checkIfIDInStorage
it works fine, however if it goes into the else and makes a call to my API it goes to the end of the function and returns false before the call returns true If I remove the return false
in canActivate
it still doesn't work. If I click on the project again after I see that it has returned true it works fine.
Console output
can activate else
before return false
in subscribe if
true
in store
Guard.ts
canActivate (route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean
{
const id = route.params.id;
if (this.checkIfIDInStorage(id)) {
console.log("checking id");
return true;
}
else {
console.log("in can activate else");
this.API.checkProjectOwnership(id).subscribe((data) =>
{
console.log("in subscribe if");
if (data.type === 'AL') {
console.log("true");
this.storeProjectID(id);
return true;
}
else {
console.log("in subscribe else ");
this.router.navigate(['/dashboard']);
}
});
}
console.log("before return false");
return false;
}
storeProjectID(id: string) {
console.log("in store");
this.session.store('id', id);
return true;
}
getProjectID() {
return this.session.retrieve('id');
}
checkIfIDInStorage(id: string) {
const storedID = this.getProjectID();
return (id === storedID);
}
API.service.ts
checkProjectOwnership(params: URLSearchParams): Observable<any> {
const URL = `${this.API}/projects/ownership?id=${params}`;
return this.auth.refreshToken()
.flatMap(() => this.authHttp.get(URL, this.headers))
.map((response: Response) => response.json())
.share()
.catch(this.handleError);
}