How to set a timeout to abort an $http.get() inside a factory or service?

和自甴很熟 提交于 2019-12-04 04:07:09

The service $http accepts, in the config object, a timeout property that answers to what you need. Have a look at the documentation, especially the part about the config object:

timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.

Also, notice that you're using promises in an inefficient way. The following is a promise antipattern:

WebServiceFactory.getData = function (url) {

 var deferred = $q.defer();

 $http.get(url)
   .then(
   function (response) {

     deferred.resolve(...);

   }, function (rejected) {

     deferred.reject(...);
   }
 );
 //Promise to be returned
 return deferred.promise;
}

You could have simply:

WebServiceFactory.getData = function (url) {
    return $http.get(url);
}

With a timeout of 3 seconds it would be:

Service:

WebServiceFactory.getData = function (url) {
    return $http.get(url, {timeout: 3000});  // <-- timeout applies ONLY for this call
}

Controller:

WebServiceFactory.getData(url).then(
    function (result) {
      doctorsCtrl.hideLoading();
      doctorsCtrl.specialties = StorageFactory.specialties = result.data;
    }, function (rejected) {
      doctorsCtrl.hideLoading();
      doctorsCtrl.showAlert();
    }
  );

Notice also that you're calling hideLoading both in case of success and error. You can call it once, in a chained finally handler:

// ...
.finally(function () {
    doctorsCtrl.hideLoading();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!