アーカイブ

AngularJSコードサンプル(http interceptor)

AngularJS : 1.6.5
Bootstrap : 3.3.7
 
※v1.2.3のサンプルはこちら
 

(1)$httpサービスのInterceptor



レスポンスデータ

名前 年齢 住所
{{item.id}} {{item.name}} {{item.age}} {{item.address}}

<button ng-click="getFriends(true)">データ取得</button><br />
<button ng-click="getFriends(false)">データ取得(エラー)</button><br />
<strong>レスポンスデータ</strong><br />
    <table class="table table-striped">
  <thead>
    <tr>
      <th>№</th><th>名前</th><th>年齢</th><th>住所</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="item in friends" >
      <td>{{item.id}}</td><td>{{item.name}}</td><td>{{item.age}}</td><td>{{item.address}}</td>
    </tr>
  </tbody>
</table>

1)アノニマスのファクトリを使ってinterceptorを設定する方法
var demoApp = angular.module('demoApp', []);
demoApp.config(function($httpProvider) {
  $httpProvider.interceptors.push(function ($q) {
    return {
      request: function(config) {
        config.headers.Authorization = 'Basic xxxx';
        console.log('Interceptor:request', config.headers);
        return config;
      },
      requestError: function(rejection) {
        console.log('Interceptor:requestError', rejection);
        return $q.reject(rejection);
      },
      response: function(response) {
        console.log('Interceptor:response', response);
        return response;
      },
      responseError: function(rejection) {
        console.log('Interceptor:responseError', rejection.statusText);
        return $q.reject(rejection);
      }
    }
  })
});

demoApp.controller('intceptCtrl', function ($scope, $http) {
  $scope.getFriends = function (tf) {
    var svrURL = (tf ? "friends.json" :"invalid-url.php");
    var config = {};
    $http.get(svrURL, config)
      .then(function onSuccess(response) {
        console.log('Client:response', response.status);
        $scope.friends = response.data;
      }, function onError(response) {
        console.log('Client:responseError',response.status);
        $scope.friends = [];
      });
  };
});

2)サービスとしてinterceptorを登録する方法
var demoApp = angular.module('demoApp', []);
demoApp.factory('myInterceptor', function($q) {
  return {
    request: function(config) {
      config.headers.Authorization = 'Basic xxxx';
      console.log('Interceptor:request', config.headers);
      return config;
    },
    requestError: function(rejection) {
      console.log('Interceptor:requestError', rejection);
      return $q.reject(rejection);
    },
    response: function(response) {
      console.log('Interceptor:response', response);
      return response;
    },
    responseError: function(rejection) {
      console.log('Interceptor:responseError', rejection.statusText);
      return $q.reject(rejection);
    }
  };
});
demoyApp.config(function($httpProvider) {
  $httpProvider.interceptors.push('myInterceptor');
});

関連記事の目次