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

Jek*_*eka 7 angularjs angularjs-service angularjs-factory ionic-framework ionic

getData(url)在我的工厂中使用 以下方法$http.get(url)来从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;
    }
Run Code Online (Sandbox Code Playgroud)

它工作正常,但我需要中止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();
    }
  );
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*zos 9

该服务$http在配置对象中接受一个timeout可满足您需要的属性.看一下文档,特别是关于config对象的部分:

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

另外,请注意您以低效的方式使用promises.以下是一个承诺反模式:

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;
}
Run Code Online (Sandbox Code Playgroud)

你可以简单地说:

WebServiceFactory.getData = function (url) {
    return $http.get(url);
}
Run Code Online (Sandbox Code Playgroud)

超时为3秒,它将是:

服务:

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

控制器:

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

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

// ...
.finally(function () {
    doctorsCtrl.hideLoading();
}
Run Code Online (Sandbox Code Playgroud)