【发布时间】:2015-04-22 10:26:29
【问题描述】:
我创建了一个 JS 对象,其方法调用 $http 来检索一个值,但是当 $http 完成后我想将此值分配给一个属性,我似乎无法获得这个值:
属性 this.user 总是以承诺本身结束,但我想分配从 XHR 请求返回的值或失败时未定义的值,我认为这是一个上下文问题,我只是不知道如何解决它
var Ticket = function(numint, company_id, user_id, title, description, priority, status, assignation, created_at) {
this.numint = numint;
this.company_id = company_id;
this.user_id = user_id;
this.title = title;
this.description = description;
this.priority = priority;
this.status = status;
this.assignation = assignation;
this.created_at = created_at;
this.user = undefined;
this.getUser = function() {
if(this.user_id === undefined)
return false;
var http =
$http({
method : 'GET',
url : '/users/' + this.user_id,
timeout : 100000,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
});
this.user = http
.then(
function(data) {
return data;
}
,
function() {
return undefined;
});
return http;
}
};
【问题讨论】:
-
$http是一个异步操作 - 你不能return来自成功处理程序的值并分配它this.user- 你必须在处理程序内部分配它:self.user = data;并分配var self = this;事先 -
是的,虽然是这样,但是我如何在处理程序中引用 this.user ???如果我输入 this.user... 上下文错误,则 this 指向处理程序