Angularjs$http then函数
我创建了一个JS对象,该对象使用一个调用$http的方法来检索一个值,但是当$http完成后,我想将这个值分配给一个属性,我似乎无法获取这个值: 属性this.user总是以承诺本身结束,但我想分配从XHR请求返回的值或失败时未定义的值,我认为这是一个上下文问题,我只是不知道如何修复它Angularjs$http then函数,angularjs,http,promise,Angularjs,Http,Promise,我创建了一个JS对象,该对象使用一个调用$http的方法来检索一个值,但是当$http完成后,我想将这个值分配给一个属性,我似乎无法获取这个值: 属性this.user总是以承诺本身结束,但我想分配从XHR请求返回的值或失败时未定义的值,我认为这是一个上下文问题,我只是不知道如何修复它 var Ticket = function(numint, company_id, user_id, title, description, priority, status, assignation, crea
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;
}
};
var http
是一个promise对象,因为Angular的$http
服务的返回值是一个promise()。使用.then()
在AJAX请求返回且承诺得到解决后获取返回值
var self = this;
http.then(function (data) {
self.user = data;
});
将其指定给其他值或!或者我们,捆绑
$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));
$http
是一个异步操作-您不能从成功处理程序返回值并将其分配给此。用户
-您必须在处理程序内部分配它:self.user=data代码>和赋值var self=this
beforehandyes我想是的,但是我如何在处理程序中引用this.user???如果我键入此。用户。。。上下文是错误的,this指向handler我试过这个,它不起作用,this指向函数处理程序,而不是我的object@GabrielMatusevich,我编辑了Morgan的问题,修正了这个referenceslight差异。我用了。成功,所以数据就是实际数据。否则我就得做数据。data@GabrielMatusevich可以使用.success()返回数据,而不是使用.then()返回整个响应对象。请记住,.success()和.error()是Angular的$http和$resource服务独有的方便函数。因此,如果更改代码,使$http不会返回承诺(例如从缓存加载数据),那么.success()和.error()将不再存在。可以找到关于.success()、.error()和.then()之间差异的更深入解释。
$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));