I'm trying to work with Auth guards in angular. I have a httpcall that sets a true/false value based on a response back from an HTTP call. The problems are: 1) httpClients return an observable 2) the httpClient subscription needs to happened before the Authorized method gets called, that way the hasSessionFlag is already set.
DUAL SERVICE .TS
hasSession() {
return this.http.get<{}>('API CALL', {
withCredentials: true,
observe: 'response'
}).subscribe((res=>{
if(res.status === 200) {
this.hasSessionFlag = true;
} else {
this.hasSessionFlag = false
}
}));
}
//Check if all the logical conditions of the user sessions pass*
isAuthorized(): boolean {
if (this.hasSessionFlag) {
this.authService.login();
} else {
this.dualLoginRedirect();
}
}
canActivate(): boolean {
return this.isAuthorized();
}
ROUTER.TS
{
canActivate: [DualLogonService],
path: 'test',
component: TestPageComponent
}
As per your latest code, I think this is what you want to do:
If API returns status is 200 then you want to call "this.authService.login();
" otherwise "this.dualLoginRedirect();
"
[As per your code at the time of writing this answer - Your isAuthorized()
method does not return boolean instead it returns undefined. It must return a boolean or an observable of boolean or promise. I am assuming that in case of status is 200 then it will return true
otherwise it will return false
]. With this assumption, you can have only canActive()
method like this:
canActive(): Observable<boolean> {
return this.http.get<{}>('API CALL', {
withCredentials: true,
observe: 'response'
})
.pipe(
map(res => {
if(res.status === 200) {
//OR DO here whaterevr you want to do
this.authService.login();
//return true will render the associated component
//i.e. pass the guard
return true;
} else {
this.dualLoginRedirect();
//return false will fail the guard.
return false;
}
})
);
}
Your guard service will automatically subscribe to the returned observable of canActivate()
method.
Also, notice that in this approach there is no class members are declared. Although if your guard needs it just declare them and use them as per your requirements.