我几乎所有的REST请求都需要用户ID。
当我登录一个用户时,我会将token传递到本地存储,并将ID传递给user.service.ts(通过函数setUserId(userId);)。但是当我仅通过令牌进行用户身份验证(用户已登录但页面已刷新),我尝试从User对象中获取userID(通过token从REST请求中获取用户对象)。
我的代码的这部分看起来像:
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;
});
}
}
当任何请求要求用户ID时,我使用getUserId()函数并检查用户ID是否已定义。如果已定义,则响应此数据,但如果未定义,则希望从getUser()函数中获取此数据。
我无法解决一个问题 - 此请求是异步的,例如“任务”服务将userId值设置为未定义 - 不等待此新值。
如何解决这个问题?
---编辑
这里有一个请求 - 它不等待响应;
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());
}
() => {}
而不是function() {}
,那么你就不需要使用丑陋的$self
hack,而可以直接使用this.
。 - Günter Zöchbauer