如何设置超时以中止工厂或服务中的$ http.get()?

时间:2015-10-20 19:00:36

标签: angularjs ionic-framework ionic angularjs-service angularjs-factory

我的工厂中有以下方法getData(url),它使用$http.get(url)从网址获取数据

angular
  .module('az-app')
  .factory('WebServiceFactory', function ($http, $q) {

   var WebServiceFactory = this;


   WebServiceFactory.getData = function (url) {

      var deferred = $q.defer();

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

          deferred.resolve({
            data: response
          });

        }, function (rejected) {

          deferred.reject({
            data: rejected
          });
        }
      );
      //Promise to be returned
      return deferred.promise;
    }

它工作正常,但我需要中止http.get和/或拒绝承诺,以便我可以显示来自我的控制器的错误消息,其中包含以下方法:

var getSpecialties = function (type) {
  doctorsCtrl.showLoading();

  var url = "example.com";

  WebServiceFactory.getData(url)
    .then(
    function (result) {
      doctorsCtrl.hideLoading();


      var specialtiesArray = result.data.data;

      StorageFactory.specialties = specialtiesArray;
      doctorsCtrl.specialties = StorageFactory.specialties

      //I WANT TO TRIGGER THIS REJECTED FUNCTION when timeout time is finished
    }, function (rejected) {
      doctorsCtrl.hideLoading();
      doctorsCtrl.showAlert();
    }
  );
}

1 个答案:

答案 0 :(得分:9)

服务$http在配置对象中接受timeout属性,该属性可以满足您的需求。查看documentation,尤其是关于config对象的部分:

  

timeout - {number | Promise} - 超时(以毫秒为单位),或承诺在解决时应中止请求。

另外,请注意您以低效的方式使用承诺。以下是 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;
}

你可以简单地说:

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

超时为3秒时,它将是:

<强>服务

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

<强>控制器:

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

另请注意,在成功错误的情况下,您都会调用hideLoading。您可以在链式 finally 处理程序中调用它一次:

// ...
.finally(function () {
    doctorsCtrl.hideLoading();
}