I'm using angular 1.4.1
I use two webservices from a server ( i cannot edit them )
/institutions
who return me a list of institutions with ids/institution/XXX/collections/
( with XXX is a institution id) who return me the collections of the current institution
I create a service function (
getInstitutions()
) who use this webservices to get all the data about institutions and there sub collections :var singleton_institutions = null ; this.getInstitutions = function(){ var getHrefCollections = function(links){ for(var l in links){ if(links[l]["rel"] == "collections"){ return links[l]["href"]; }} return null ; }; if(singleton_institutions != null){ // don't reload the data if already loaded return $timeout( function(){ return singleton_institutions ; }, 0); }else { var institutions = []; var url = $rootScope.api + "institutions"; return $http({ method: 'GET', url: url }).then( // we have the institutions list, now get each sub collections function successCallback(response) { institutions = response.data; var promises = []; for (var i in response.data) { var url = getHrefCollections(response.data[i]["links"]); promises.push( //Push the promises into an array $http({ method: 'GET', url: url }).then(function successCallback(response) { return response.data; }) ); } return $q.all(promises); // Resolve all promises before going to the next .then }, function errorCallback(response) { console.log(response); } ).then( function (resultArray) { // formating the data for (var i in resultArray) { institutions[i]["collections"] = resultArray[i]; institutions[i]["institutionname"] = tools_getInstitutionName(institutions[i]["institutioncode"]); } singleton_institutions = institutions; return singleton_institutions ; }, function (error) { console.log(error); } ); } };
The problem :
In my service function i make a chained promise with $q, this work good, it take few seconds because it launch approximatly 30 https call (one per institution).
In the application initialization, this function are called twice in approximatly the same time.
So the first call don't have time to finish and to init singleton_institutions
before the second call so i have 60 http's call instead of half.
//call from a controller A
services.getInstitutions().then(function (institutions) {...}); // take few seconds to load the datas
//call from a controller B in near the same time
services.getInstitutions().then(function (institutions) {...}); // so this will make all the data load again because the first call is not finished
- QUESTION :
How to prevent services.getInstitutions()
to get the data if another call is not finished yet.