I am trying to do the next... i have an API where i send a JWT token by POST to be verified if it is valid/expired,
so in my angular login service i have a method like this.
isUserlogged() {
return this.httpClient.get(`${this.URL}/verifyToken`, { headers: { 'authorization': localStorage.getItem('token') } })
}
this subscription returns a boolean, all ok here.
Now i am implementing Guards in my app, so now i want to use that boolean value for my canActivate method to block the access... i read that i need to return, true or false in this method to allow or block the access to the routes that i configured before
So i am doing something like this inside of canActivate.
this.loginService.isUserlogged().subscribe((response: boolean)=>{
if(response){
return true;
}
return false;
});
but this is returning void... why? how can i retreive the true or false value from this subscription?
Don't return a subscription from inside a route a guard, If not boolean then return an Observable of boolean.
return this.loginService.isUserlogged()
Since "isUserlogged" is already giving you a boolean output here, you can directly return the Observable.
If isUserlogged()
is not returning a boolean then pipe it.
return this.loginService.isUserlogged().pipe(
map((resp) => {
// some logic here, check the return.
// based on the logic
if (something) {
return true
}
return false
})
)
This will all work if your API
call is getting finished and returning a proper response. If your API is returning void, then you have not provided any details regarding your API call and your API works. (First test your API with an HTTP client, like: Postman, if that is giving a proper response then integrate it with Angular)