2014-05-12 19 views
1

我在使用ng-view的angularjs中創建了一個應用程序。通過路由提供者,四個不同的模塊被加載到ng視圖中。 在每個模塊I米以下方式發送HTTP請求: -如何在調用請求的控制器失去作用域時在angularjs中取消http請求

var requestManager = { 
    "locations": {}, 
    "employees": {}, 
    "items": {}, 
    "templates": {} 
}; 
sendRequestToServer = function (reqObj) { 
    var reqObj = reqObj, 
     httpObj = {}, 
     defer = $q.defer(); 
    httpObj = { 
     method: reqObj.method, 
     url: baseUrl + reqObj.url, 
     timeout: 90000 
    }; 
    if (reqObj.method == 'GET') { 
     httpObj['params'] = reqObj.data; 
     if (reqObj.uniqueId) { 
      httpObj['headers'] = { 
       'uniqueId': uniqueId 
      } 
     } 
    } else if (reqObj.method == 'POST' || reqObj.method == 'PUT') { 
     httpObj['headers'] = { 
      'Content-Type': 'application/x-www-form-urlencoded' 
     }; 
     httpObj['data'] = reqObj.data; 
    } 
    requestManager[reqObj.moduleName][reqObj.requestName] = $http(httpObj).success(function (data, status, headers, config) { 
     var dataObj = { 
      data: data, 
      status: status, 
      headers: headers, 
      config: config 
     }; 
     defer.resolve(dataObj); 
    }) 
     .error(function (data, status, headers, config) { 
      var dataObj = { 
       data: data, 
       status: status, 
       headers: headers, 
       config: config 
      }; 
      defer.reject(dataObj); 
     }); 
    return defer.promise; 
} 

現在,我的要求是: - 當從一個模塊到另一路由變化,我想中止這是在中間的請求服務器通信。 要做到這一點我在聽的破壞事件: -

$rootScope.$on('destroyModule', function(event, moduleName) { 

    var requests = requestManager[moduleName] 
     , defer = $q.defer() 
     , index 
     , req; 
    for(req in requests){ 

    //Want abort the request 
     defer.reject(requests[req]); 

    } 
}) 

但它不工作..我想我]丟是錯誤的。任何人都可以幫助解決這個問題? 感謝您提前

+0

請請請不要東西,這不是一個錯誤拒絕。總是拒絕一個錯誤,因爲它會給你堆棧跟蹤。 –

+0

另外,考慮重寫你的代碼,以避免https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns#the-deferred-anti-pattern –

+0

我讀了你提供的github鏈接。但我的問題我怎麼能達到我的要求,以中止我已經發送的請求。可以請你幫我。 – Anuradha

回答

0

的破壞事件將不會觸發對$ rootScope,如果您有其它範圍,你可以聽也(可能在一個視圖控制器?),你可以連線,像這樣:

$scope.$on("$destroy", function(){ ... }); 

如果在另一方面,你只是想檢測時的位置變化,你可以這樣做:

$rootScope.$on("$locationChangeStart", function(){ ... }); 
+0

如何獲取在範圍被破壞之前已經發送的http請求的跟蹤 – Anuradha