我创建了一个JS对象,其方法调用$ http来检索值,但是当$ http完成后我想将此值赋给属性,我似乎无法能够得到这个值:
属性this.user总是以promise本身结束,但是我想分配从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;
}
};
答案 0 :(得分:2)
var http
是一个promise对象,因为Angular的$http
服务的返回值是一个promise(docs)。一旦AJAX请求返回并且承诺已解决,请使用.then()
获取返回值。
var self = this;
http.then(function (data) {
self.user = data;
});
答案 1 :(得分:0)
var Ticket = function(numint, company_id, user_id, title, description, priority, status, assignation, created_at) {
var self = this; // new code
self.numint = numint; //use self inseat
self.company_id = company_id;
this.getUser = function() {
if(self.user_id === undefined) // you had one preblem here, because "this" here is direrent to the this.user_id you neded, so use self
return false;
var http =
$http({
method : 'GET',
url : '/users/' + this.user_id,
timeout : 100000,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (data){
self.user = data
;},
function () {
self.user= undefined;
});
}
};
答案 2 :(得分:0)
将此值分配给不同的值或!或者我们.bind。
$http({
method : 'GET',
url : '/users/' + this.user_id,
timeout : 100000,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (data){
this.user = data;
}.bind(this));