Works by

Ren's blog

@rennnosuke_rk 技術ブログです

【AngularJS】$httpによる通信を任意のタイミングで中断する

$httpのタイムアウト

AngularJSではHTTPリクエストを投げるためのサービス$httpが提供されていますが、
引数configのプロパティtimeoutを設定することで、HTTPリクエストをタイムアウトさせることができます。

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

AngularJS: API: $httpより引用

timeoutには整数型とPromise型オブジェクトを設定することができます。
整数型を設定した場合には指定整数ミリ秒後にリクエストをタイムアウトします。
Promise型を設定した場合には、Promise生成元のDeferedオブジェクトに対してDefered.resolve()がコールされたタイミングでリクエストがタイムアウトされます。

Usage

let mod = angular.module('myApp', []);
mod.controller('MyAppCtrl', ['$scope', '$http', '$q', '$timeout', function($scope, $http, $q, $timeout){
                             
  $scope.onButtonClick = function onButtonClick() {
    
    let defered = $q.defer();

    let success = function(response) {
      $scope.message = "success!";
      $scope.response = response;
    };

    let error = function(error) {
      $timeout(function(){
        $scope.message = "error.";
        $scope.response = error;
      });
    };

    // 1) ミリ秒指定
    $http({ method: "GET", url : "/hoge/fuga/api", timeout: 3000 })
    .then(success)
    .catch(error);

    // 2) Promiseオブジェクトを指定
    $http({ method: "GET", url : "/hoge/fuga/api", timeout: defered.promise })
    .then(success)
    .catch(error);           
    
    // Promiseオブジェクトをtimeoutに指定した場合、Defered.resolve()を呼ぶとタイムアウトする
    // 1) と同じ挙動
    $timeout(function(){
      defered.resolve();
    }, 3000);

  };
 
}]);