I need user ID in almost all REST requests.
When I log-in a user, I pass token to local storage and ID to user.service.ts (by function setUserId(userId);) but when I authenticate user only by token (user is logged but page was refreshed) I try to get userId from User object (get user object from REST request by token).
This part of my code look like:
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;
});
}
}
When any request ask for user ID i use getUserId() and I check if user Id is defined. If is defined i response with this data, but if not - I want get this data from getUser() function.
I can't solve one problem - this request is async and for example "task" service set userId value as undefined - doesn't wait on this new value.
How can I manage with this problem?
---EDIT
Hire is a request - it doens't wait on 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());
}
() => {}instead offunction() {}, then you don't need to use the ugly$selfhack and can instead just usethis.