javascript - AngularJS ajax http promise 返回附加数据

标签 javascript jquery ajax angularjs

在 Promise then 函数中,当您收到数据对象时,它会被另一个数据对象包装,例如

data = Object {data: Object, status: 200, config: Object, statusText: "OK"}

如何避免这种情况。您需要访问您的变量,例如 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;
};

最佳答案

只需从您的“服务”返回数据部分即可。而且您可以放弃多余的 promise ,因为 $http 已经是一个 promise 。

$scope.test().then(function(data) {
  console.log(data);
});

$scope.test = function() {
  return $http('json/requestKey.json').then(function(response) {
    return response.data;
  });
};

关于javascript - AngularJS ajax http promise 返回附加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31848539/

相关文章:

javascript - 如何将用户文本输入数据存储到 native react 对象数组中?

jquery - 将背景图像缩放到部分 - bootstrap

javascript - 将下拉列表中的值添加到 html 属性

javascript - 提交后如何关闭引导模式?

javascript - 当我尝试使用 ajax post 将值从 JavaScript 发送到 PHP 时出现错误值

javascript - 我如何知道 XHR 已使用 readState 发送到服务器?

javascript - Ajax - 跨域请求是否返回请求头?

javascript - 复选框填充表单字段

javascript - setTimeout 到 addClass,然后检查元素是否有Class

javascript - jQuery - 滚动标题动画