I am currently grappling with the challenge of writing an angular http interceptor in plain TypeScript. The JavaScript code that I am attempting to convert is as follows:
.config(['$httpProvider', function ($httpProvider) {
var interceptor = ['$rootScope', '$q', 'httpBuffer', function ($rootScope, $q, httpBuffer) {
function success(response) {
return response;
}
function error(response) {
if (response.status === 401 && !response.config.ignoreAuthModule) {
var deferred = $q.defer();
httpBuffer.append(response.config, deferred);
$rootScope.$broadcast('event:auth-loginRequired', response);
return deferred.promise;
}
// otherwise, default behaviour
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
};
}];
$httpProvider.responseInterceptors.push(interceptor);
}])
The initial sections are straightforward - create a class with a constructor that accepts the three dependencies $rootScope
, $q
and httpBuffer
. Also include two private methods success
and response
.
class MyInterceptorClass {
constructor(private $rootScope: ng.IRootScopeService, private $q: ng.IQService, private httpBuffer: HttpBuffer) {
}
private success(response: ng.IHttpPromiseCallbackArg<any>): ng.IHttpPromiseCallbackArg<any> {
return response;
}
private error(response: ng.IHttpPromiseCallbackArg<any>): ng.IHttpPromiseCallbackArg<any> {
if (response.status == 401 && !((<any>response.config).ignoreAuthModule)) {
var deferred = this.$q.defer();
this.httpBuffer.append(response.config, deferred);
this.$rootScope.$broadcast('event:auth-loginRequired', response);
return deferred.promise;
}
// Otherwise, default behavior
return this.$q.reject(response);
}
}
Additionally, ensure the registration of the interceptor is clear:
.config(['$httpProvider', ($httpProvider: ng.IHttpProvider)=> {
$httpProvider.responseInterceptors.push(['$rootScope', '$q', 'httpBuffer', MyInterceptorClass]);
}]);
The part causing me difficulty is the final section of the original JavaScript code - specifically the return value of an anonymous function. How can I replicate this in TypeScript? It seems like this would be a nameless method in TypeScript, but unfortunately that is not supported.