I am calling an AJAX on load from a controller using service but before i get the response for the first call, I have to call same request again from a different controller. currently the second request giving an error since the first did not have any response.
Controller Code :
$scope.getNavigationDetails = function(){
topNavService.getNavigationMenuDetails().then(function(result){
$scope.menuItemInfo = result;
})
};
service code:
var menuInfo, alreadyRun = false, deferred = $q.when(), firstRun= $q.defer();
this.getNavigationMenuDetails = function(){
if(this.menuInfo === undefined && !alreadyRun) {
alreadyRun = true;
// If menu is undefined or null populate it from the backend
return $http.get("/etc/designs/bookfairs/jcr:content/page/header-ipar/header/c-bar.getMenuDetails.html?id="+Math.random()).then(function(response){
this.menuInfo = response.data;
firstRun.resolve(response);
//return this.menuInfo;
});
} else if(!this.menuInfo && alreadyRun){
// Otherwise return the cached version
console.log('waiting for the first promise to be resolved ');
firstRun.then(function(response) {
console.log('resolving the promise');
deferred.resolve(response);
});
//return $q.when(this.menuInfo);
}else {
deferred.resolve(response)
}
return deferred.promise;
}
Second controller/call
topNavService.getNavigationMenuDetails().then(function(data) {
$scope.productId = data.isLoggedin;
$scope.linkParam = '?productId=' + $scope.productId;
});
Actual result should be before getting the response for first call, second call should not happen.