【问题标题】:How to get a value from returned result "Promise {$$state: Object}"如何从返回的结果“Promise {$$state: Object}”中获取值
【发布时间】:2016-05-05 14:17:20
【问题描述】:

我有这个函数,其中 GetDataFactory.getDataById(reqData) 是带有 $http 请求的函数并返回正确的数据,当这个数据到达时我想在另一个函数中使用它,但是这种方式一直返回我“Promise {$$state : 对象}"

    $scope.getData = function(id) {
                    var reqData = {
                        "id": id,
                        "access_token": $scope.access_token
                    };
                    var foo  =  GetDataFactory.getDataById(reqData).then(function(response) {
                        var foo = response.data[0];
                        return foo;
                    });

                    console.log(foo); // prints "Promise {$$state: Object}" 
        return foo;
}

$scope.anotherFunction = function(){
    var id;
    var bar = $scope.getData(id);
}

我在问如何在 $http 请求成功后返回正确的数据值,然后将其返回到另一个函数并对这些数据做任何我想做的事情?分配给 $scope.foo 类型变量和超时不是一个选项

【问题讨论】:

  • foo.then(function (value) { /* do something with the value */ });

标签: angularjs ionic-framework angular-promise


【解决方案1】:

因为 getData 函数发出一个异步请求,所以在访问它返回的数据之前,您总是必须等待它完成。您的 anotherFunction 应如下所示:

var bar
$scope.getData(id).then( function(response) {
    bar = response.data
})

您可能还想重构 getData 函数以仅从 GetDataFactory.getDataById 返回承诺,因此它看起来像这样:

$scope.getData = function(id) {
     var reqData = {
         "id": id,
         "access_token": $scope.access_token
      };
      return GetDataFactory.getDataById(reqData)
};

您已经在服务中隔离了数据检索。 getData 函数看起来有点矫枉过正,但在不了解您的所有要求的情况下,也许不是。

【讨论】:

    猜你喜欢
    • 2021-07-23
    • 2021-08-25
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 2015-07-15
    相关资源
    最近更新 更多