【问题标题】:Return data from http inside function从http内部函数返回数据
【发布时间】:2015-12-29 20:00:00
【问题描述】:

我正在使用 thisthis 引用,从函数内的 http 请求返回数据:

function getdetails(id) {

            var datafordetails = {
                data1: {
                    item1: "",
                    item2: ""
                },
                data2: {
                    item3: "",
                    ID: id
                }
            };

            var jsonDataDetails = JSON.stringify(datafordetails);
            return $http({
                url: "http://...",
                method: "POST",
                data: jsonDataDetails,
                dataType: "json",
                timeout: 5000,
                contentType: 'application/json; charset=utf-8'
            })
                .then(function (res) {
                    var data = res.data;
                    responsedata=data.d;
                    return responsedata;

                },function (error) {
                    $scope.status = status;
                    console.log("Unable to update. No internet?");
                })
        }

我的目标是 var testing = getdetails('12345'); 为我提供该 ID 的响应数据,但我会返回 Promise {$$state: Object...

我做错了什么?非常感谢!

【问题讨论】:

    标签: javascript angularjs asynchronous promise angular-promise


    【解决方案1】:

    你得到的输出只不过是一个由$http.get 方法返回的promise 对象。基本上你需要把.then函数放在getdetails2函数上,以便在resolve/reject时从promise对象获取数据。

    代码

    getdetails2('12345').then(function(data){ //success callback
       //you will get data here in data parameter of function,
       var testing = data;
    }, function(error){ //error callback
       console.log(error)
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 2011-08-01
      • 1970-01-01
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多