5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

毎回必ず忘れて調べてしまうAngularJS1.x系のHttpInterceptor(TypeScript)の定義方法を自分のためだけにここに記す。

Posted at

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)
}])
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?