如何发出多个http请求?

飞猫

我的父控制器和子控制器中有一个HTTP请求:

上级控制器

//Product is a $resource object that return http request as a promise.
Product.getItem()
   .then(function(items) {
      $scope.items = items
      //do something in the parent controller.
})

子控制器

Product.getItem()
   .then(function(items) {          
      $scope.items = items
      //do something in the child controller
})

产品工厂

angular.module('testApp').factory('Product', function($http,$q) {
    var service = {}
    service.getItem = function() {
        return http.$get('api/url');
    }
    return service; 
})

当我在某些页面中时,将启动子控制器。问题是当我启动这些页面时,代码将向api / url发出双http请求,因为父级和子级控制器都发出了请求。尽管我的应用程序仍然可以运行,但是我想知道是否有更好的方法来解决它。谢谢您的帮助!

p

编辑:我调查了菲尔的评论,并修正了(改写)我的例子。底部的塞子反映了这些变化。这是更新的代码:

app.controller('MainCtrl', function($scope, getStore) {
  getStore.get().then(function(data) {
    $scope.data = data
  })
});
app.controller('ChildCtrl', function($scope, $timeout, getStore) {
  $timeout(function() {
    getStore.get().then(function(data) {
      $scope.test = data
    })
  },3000)

});

app.factory('getStore', function($http, $q) {
  var self = this;
  var data;
  return {
    get: function() {
      if (data) {
        console.log(data);
        console.log('already got data')
        return $q.when(data)
      } else {
        data = $http.get('test.json')
        .then(function(response) {
          console.log('fetched data')
          return response.data;
        })
        return data
      }
    }
  }
})

这是一种解决方案-将$ http.get分离到工厂并在其中存储值。工厂是单例,因此两个控制器都可以访问和检查数据。

JS:

app.controller('MainCtrl', function($scope, getStore) {
  $scope.data = getStore.get()
});
app.controller('ChildCtrl', function($scope, $timeout, getStore) {
  $timeout(function() {
    $scope.data = getStore.get()
    var check = getStore.checkData();
    console.log('Data in store: ' + angular.toJson(check));

  },1000)
  $scope.getData = function() {
    console.log(getStore.get());
  }
});

app.factory('getStore', function($http) {
  var self = this;
  return {
    data: undefined,
    get: function() {
      if (self.data) {
        console.log('already got data')
        return self.data
      } else {
        $http.get('test.json')
        .success(function(data) {
          console.log('no data found');
          self.data = data;
          console.log(self.data);
          return self.data;
        })
      }
    }
  }
})

它只是运行检查以查看该值是否已存储,如果已存储,则返回它;如果不是,则返回,存储并返回它。

柱塞

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章