繁体   English   中英

将数据从异步调用存储到AngularJS中的变量

[英]Store data from asynchronous call to a variable in AngularJS

以下是我尝试使用promise的代码,用于将数据从异步调用保存到变量中,但无法正常工作。 我在寻求帮助时感到很陌生,发现承诺在这些情况下会有所帮助,但我无法申请,请让我知道我在这里做错了什么-

angular.module("app").controller("myCtrl", function($scope, $http, $q) {
    var deferred = $q.defer();

    var data = $http.get("/api/events").success(function(response){
    deferred.resolve(response);
    return deferred.promise;
    // ALSO tried return response;
    })
    console.log("DATA--");
    console.log(data);
});

编辑 -

我正在尝试达到两个 APIS-

1)从第一个API匹配中创建ID数组。

2)循环到数组,以根据ID匹配第二个API。

3)连接来自数组1和array2的一些数据。

我正在尝试做的更具体的案例,但是发现使用了promise-

http://pastebin.com/ZEuRtKYW

在异步调用中获得响应时,请将其存储在作用域变量中。 然后,您可以在控制器内的任何位置访问该范围变量。

 angular.module("app").controller("myCtrl", function($scope, $http) {
         $http.get("/api/events").success(function(response){
         $scope.response = response;     
        })

    });

我将按以下方式进行操作:

$http.get('data.json').success(function (result) {
    $scope.result = result;
}).then(function (data) {
    var result = data.data.key;

    var promises = result.map(function (val) {
        var deffered = $q.defer();

        $http({
            method: 'GET',
            url: 'data-' + val.id + '.json'
        })
        .success(function (x) {
            deffered.resolve(x);
        })
        .error(function () {
            deffered.reject();
        });

        return deffered.promise;
    });

    $q.all(promises).then(function (result) {
        $scope.resolvedData = result;
    });

});

根据第一个调用的结果将所有promise映射到一个promise数组。 在此地图函数内部创建一个新的promise,并在成功函数中解决它。 确保您返回实际的承诺!

之后,您可以使用$q.all(promises)获得所有已解析的数据。 这样,您对数据库的调用不限于2。您可以根据第一次调用中检索到的数据进行任意数量的调用。

柱塞

编辑 :不确定是否可以修改服务,但是最好只用一个电话就可以实现。 例如:

get '/api/events' --> returns just the events
get '/api/events?includeDetail=true' --> returns the events + the details of an event

我认为这可以通过以下方式完成:

angular.module("app").controller("myCtrl", function($scope, $http, $q) {

   var ids = [],
       q1 = $q.defer(), 
       q2 = $q.defer();
       d1 = $http.get("/api/events").success(function(data){
               q1.resolve(data);
               angular.forEach(data, function(id) {
                  ids.push(id); 
               });
            }).error(function(err){
                q1.reject("Ooops!!")
            });

   var promises = [];

   angular.forEach(ids, function(id) {
      var promise = $http.get("/api/events", {id:id})
                    .success(function(data){
                        q2.resolve(data);
                    }).error(function(err){
                        q2.reject("Ooops!!")
                    });
      promises.push(promise);
   });

   $q.all(promises)
     .then(function(values) {        
       console.log(values);
   });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM