1.Interceptor作る
httpInterceptor.ts
export default class HttpInterceptor implements ng.IHttpInterceptor {
static factory($q: ng.IQService,
$log: ng.ILogService): HttpInterceptor {
return new HttpInterceptor($q, $log)
}
constructor(
private q: ng.IQService,
private log: ng.ILogService) {
}
request = (config: ng.IRequestConfig): ng.IRequestConfig => {
// 必要なヘッダ情報詰め込む
config.headers['Hoge'] = 'Hoge'
this.log.debug('Request:', config)
return config
}
requestError = (rejection: any)=> {
// ステータスによって処理を分岐
if (rejection.status == 404) {
}
return this.q.reject(rejection)
}
response = <T>(response: ng.IHttpPromiseCallbackArg<T>): ng.IPromise<T> => {
this.log.debug('Response:', response)
return this.q.when(response)
}
responseError = (rejection: any)=> {
// ステータスによって処理を分岐
if (rejection.status == 404) {
}
return this.q.reject(rejection)
}
}
2.Interceptor登録する
app.ts
import angular = require('angular')
import HttpInterceptor from './interceptors/http-interceptor'
let app = angular.module('App', [
// 必要なmodule入れてください
]);
app.config(['$routeProvider', '$httpProvider', '$logProvider',
($routeProvider: ng.route.IRouteProvider,
$httpProvider: ng.IHttpProvider,
$logProvider: ng.ILogProvider)=>{
// 開発中はデバッグメッセージを表示に
$logProvider.debugEnabled(true);
$routeProvider
.when('/', {
template: require('../views/login.html'),
controller: 'LoginCtrl',
controllerAs: '$ctrl'
})
.otherwise({
redirectTo: '/'
});
// interceptor登録
$httpProvider.interceptors.push(HttpInterceptor.factory)
}])