繁体   English   中英

如何发出多个http请求?

[英]How to make multiple http requests?

我的父控制器和子控制器中有一个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请求,因为父级和子级控制器都发出了请求。 尽管我的应用程序仍然可以运行,但是我想知道是否有更好的方法来解决它。 谢谢您的帮助!

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

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;
        })
      }
    }
  }
})

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

Plunker

暂无
暂无

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

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