0

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.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • Give a look: https://stackoverflow.com/a/33816085/7733724 – Sam Jun 24 '19 at 07:04
  • Not 100% sure what you are doing here or what framework you are using but if you want something to only execute after the call is complete then put it in the `.then` which handles the response and wont execute before there is one. – Michael Jun 24 '19 at 07:05
  • 1
    I strongly recommend that if you and a peer of some sort are posting about the same website or homework, that you refrain from doing so. It is also not ok to have friends or peers vote for you. –  Jun 24 '19 at 10:59

0 Answers0