[英]AngularJS ajax http promise returns additional data
In the promise then function when you receive the data object it is wrapped with another data object like 在promise then函数中,当您收到数据对象时,它会被另一个数据对象包装,例如
data = Object {data: Object, status: 200, config: Object, statusText: "OK"}
How to avoid this. 如何避免这种情况。 you need to access your variables like data.data.myVar 您需要访问您的变量,例如data.data.myVar
var test123 = $scope.test();
test123.then(function(data){
console.log(data);
// why you need to access your data in "data.data.myValue"
},function(data){
});
$scope.test = function(){
var promise = $http(
{
method: 'GET',
dataType: "jsonp",
url: 'json/requestKey.json'
}
)
.success(function(data) {
return data;
})
.error(function(data){
//return data;
});
return promise;
};
Just return the data part from your "service". 只需从“服务”中返回数据部分即可。 And you can ditch the redundant promise since $http
is already a promise. 而且您可以放弃多余的承诺,因为$http
已经是一个承诺。
$scope.test().then(function(data) {
console.log(data);
});
$scope.test = function() {
return $http('json/requestKey.json').then(function(response) {
return response.data;
});
};
Well this is be resolved two ways 那么这可以通过两种方法解决
success()
callback of your $http
, return data.data
instead of just return data
, so that in your then()
function you will get the internal object. 在$http
的success()
回调中,返回data.data
而不是仅return data
,因此在then()
函数中,您将获得内部对象。 When you are returning, HttpResponseMessage, REST api response data in this format, 当您返回HttpResponseMessage,这种格式的REST api响应数据时,
Object {data: Object, status: 200, config: Object, statusText: "OK"}
To parse in ajax success call back, 要解析ajax成功回调,
$http.get(urlBase + '/get/' + id).then(function (response) {
var yourData = response['data'];
var yourStatusCode = response['status'];
var yourStatusText = response['statusText'];
//assign data to any other $scope object
$scope.product = yourData;
}, function (error) {
console.log('error occured!!');
});
You will do fine now, you don't need to change the response from web api now. 您现在可以做的很好,您无需立即更改来自Web API的响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.