javascript - How to make multiple http requests? -


i have http request in parent , child controller:

parent controller

//product $resource object return http request promise. product.getitem()    .then(function(items) {       $scope.items = items       //do in parent controller. }) 

child controller

product.getitem()    .then(function(items) {                 $scope.items = items       //do in child controller }) 

product factory

angular.module('testapp').factory('product', function($http,$q) {     var service = {}     service.getitem = function() {         return http.$get('api/url');     }     return service;  }) 

child controller launched when in pages. problem when launch pages, codes make double http request api/url because parent , child controllers both make requests. although app still works, wondering if there better way solve it. help!

edit: investigated phil's comments bit, , fixed (rewrote) example. plunker @ bottom reflects these changes. here updated code:

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

here 1 solution - separate $http.get factory , store value there. factories singletons, both controllers can access , check data.

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

it runs check see whether value stored or not, , returns if is, , if not, gets, stores, , returns it.

plunker


Comments