AngularJSでajaxによる通信を行うにあたって以下のような共通の処理を入れたい事がある。

  • 通信中にローディング画面を表示させたい
  • 認証エラーの時にログイン画面に遷移させたい

このような時は$httpProviderのinterceptorsプロパティを使う。

var app = angular.module('myApp', []);

app.config(['$httpProvider', function($httpProvider) {
  $httpProvider.interceptors.push(['$q', function ($q) {
    return {
      request: function(config) {
        // do something on success
        return config;
      },
      requestError: function(rejection) {
        // do something on error
        return $q.reject(rejection);
      },
      response: function(response) {
        // do something on success
        return response;
      },
      responseError: function(rejection) {
        // do something on error
        return $q.reject(rejection);
      }
    };
  }]);
}]);