In almost all REST requests, I require the user's ID to be included.
After logging in a user, I store the token in local storage and pass the ID to user.service.ts (using the function setUserId(userId);). However, when authenticating a user using only the token (e.g., if the user is already logged in but the page is refreshed), I attempt to retrieve the user's ID from the User object obtained through a REST request using the token.
This section of my code appears as follows:
getUser() {
var authToken = localStorage.getItem('authorization')
if(!this.userPromise){
let headers = new Headers();
headers.append('Content-type', 'application/json');
headers.append('Authorization', authToken);
this.userPromise = this.http.get(
'http://localhost:8080/api/user',
{ headers }
).toPromise()
.then((res) => res.json());
}
return this.userPromise;
};
getUserId(){
var $self = this;
if($self.userId){
return $self.userId;
} else {
$self.getUser().then(function(result){
$self.setUserId(result.id);
console.log(result.id);
return result.id;
});
}
}
Whenever a request requires the user ID, I utilize the getUserId() method and check whether the user ID is defined. If it is defined, I respond with that data; otherwise, I aim to retrieve the data from the getUser() function.
I am facing a problem where this request is asynchronous, causing the "task" service, for example, to receive the userId value as undefined before waiting for the updated value.
How can I address this issue?
---EDIT
Here is a sample request that does not wait for a response;
getUserTasks() {
// return this.userService.getUserId();
var userId = this.userService.getUserId();
return this.http.get(
'http://localhost:8080/api/private/'+userId+'/tasks'
// 'http://localhost:8080/api/private/1/tasks'
)
.toPromise()
.then((res) => res.json());
}