如何在获得上一个呼叫的响应之前避免AJAX请求

时间:2019-06-24 06:57:45

标签: javascript angularjs ajax http promise

我正在从使用服务的控制器加载时调用AJAX,但是在获得第一个调用的响应之前,我必须从其他控制器再次调用相同的请求。当前,第二个请求给出了错误,因为第一个请求没有任何响应。

控制器代码:

$scope.getNavigationDetails = function(){
    topNavService.getNavigationMenuDetails().then(function(result){
        $scope.menuItemInfo = result;
    })
};

服务代码:

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

第二个控制器/通话

topNavService.getNavigationMenuDetails().then(function(data) {
    $scope.productId = data.isLoggedin;
    $scope.linkParam = '?productId=' + $scope.productId;
});

实际结果应该是在获得第一次呼叫响应之前,不应发生第二次呼叫。

0 个答案:

没有答案