【问题标题】:AngularJS Service with multiple, depending queries具有多个依赖查询的 AngularJS 服务
【发布时间】:2016-03-19 16:24:35
【问题描述】:

我正在尝试创建一个 AngularJS 服务,该服务根据多个 HTTP 请求返回数据。但我似乎只是没有让它工作。

REST 调用的工作方式如下:

  • get /index 返回一个 url 数组
  • 调用每个 url,并将结果添加到数组中

我希望在服务函数调用结束时,我会收到一个包含来自 url 的所有数据的数据结构。

我当前的,有点工作的代码使用回调,但即使它在一个控制器中工作,它在另一个控制器中也不起作用。我想正确使用承诺,但我已经对成功与那时感到困惑。

我的服务:

        // Get a image
         obj.getByUrl = function (imageUrl, callback) {
                 $http.get('https://localhost:9000' + imageUrl).success(function (data) {
                     callback(data);
                 });
         }

            // Get all images
            obj.getAll = function(callback) {
                    $http.get('https://localhost:9000/1.0/images').success(function (data) {

                      if (data.status != "Success") {
                        console.log("Err");
                      }

                      var images = [];
                      for(var n=0; n < data.metadata.length; n++) {
                        var c = data.metadata[n];

                        obj.getByUrl(c, function(data2) {
                          images.push(data2.metadata);
                        });

                      }
                      callback(images);
                    });
                }

我想在控制器中使用该服务,解析如下:

resolve : {
  images: function(ImagesServices, $route) {
    return ImagesServices.getState($route.current.params.containerName)
},

我到此为止,但它只返回索引调用的数据,而不是聚合数据:

                obj.getAll3 = function() {
              var images = [];
              var promises = [];

              //var httpPromise = $http.get('https://localhost:9000/1.0/images');
              var httpPromise = $http({
                url: 'https://localhost:9000/1.0/images',
                method: 'GET',
              });

              return httpPromise.success(function(data) {
                  var data2 = data.metadata[0];
                  // angular.forEach(data.metadata, function(data2) {
                  console.log("D11: " + JSON.stringify(data2));

                  //var inPromise = $http.get('https://localhost:9000' + data2)
                  var inPromise = $http({
                    url: 'https://localhost:9000' + data2,
                    method: 'GET',
                  })
                  .success(function (data2) {
                    console.log("D2: " + JSON.stringify(data2));
                    images.push(data2);
                  });

                  promises.push(inPromise);
                  // });

                  return $q.all(promises).then(function() {
                    return images;
                  });
              });
          }

也许有人可以指出我正确的方向?

【问题讨论】:

    标签: angularjs rest http service factory


    【解决方案1】:

    这是一个典型的例子,其中链式 Promise 和使用 $q.all() 就足够了:

    /**
     * returns a promise of array of images
     */
    obj.getAll = function() {
        // start by executing the first request
        return $http.get('https://localhost:9000/1.0/images').then(function(response) {
    
            // transform the response into a promise of images
    
            // if that's not possible, return a rejected promise
            if (data.status != "Success") {
                return $q.reject("Error");
            }
    
            // otherwise, transform the metadata array into
            // an array of promises of image
            var promises = data.metadata.map(function(imageUrl) {
                return $http.get('https://localhost:9000' + imageUrl).then(function(resp) {
                    return resp.data;
                });
            });
    
            // and transform this array of promises into a promise
            // of array of images
            return $q.all(promises);
        });
    }
    

    这避免了回调反模式,并使用链接。这里解释有点长,但我写了一篇博文,希望能把上面的代码说清楚:http://blog.ninja-squad.com/2015/05/28/angularjs-promises/

    【讨论】:

    • 这是我正在寻找的确切答案。简单、优雅、干净的代码,完美运行。谢谢!我在尝试开发自己的解决方案时遇到的问题之一是我不知道 .success() 是并行工作的,而 .then() 是串行的。
    • 不是平行的。但它不允许链接承诺。无论如何,它已被弃用,不应再使用。
    猜你喜欢
    • 2016-05-17
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2020-12-14
    • 1970-01-01
    相关资源
    最近更新 更多