AngularJS : 1.2.23
Bootstrap : 3.2.0
(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) .success(function (data, status, headers, config) { console.log('Client:response', status); $scope.friends = data; }) .error(function (data, status, headers, config) { console.log('Client:responseError',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'); });