Reputation: 925
I am trying to create a simple HTTP interceptor in Angular 1.4.x (with ES6 and Babel). The only thing it needs to do is redirect to an error page if a HTTP 500 is detected. The code:
app/middleware/securityInterceptor.service.js
export default class SecurityInterceptorService {
constructor($q, $location, config) {
'ngInject';
this.$location = $location;
this.config = config;
this.$q = $q;
}
responseError(rejection) {
var deferred = this.$q.defer();
if (rejection.status === 500) {
this.$location.path(this.config.errorPagePath);
}
deferred.reject(rejection);
return deferred.promise;
}
}
Now I receive an unknown provider error while trying to run the application saying that the SecurityInterceptorService
is unknown. So I took a look at how it is registered. However, I don't see any obvious errors:
index.module.js
import interceptorConfig from './index.interceptors';
import SecurityInterceptorService from '../app/middleware/securityInterceptor.service';
// other imports
angular.module('app', ['ngTouch' /*, other dependencies */])
.config(interceptorConfig)
.service('securityInterceptorService', SecurityInterceptorService)
// other declarations
index.interceptors.js
export default function interceptorConfig($httpProvider, securityInterceptorService) {
'ngInject';
// Security interceptor
$httpProvider.interceptors.push(securityInterceptorService);
}
I can enter the interceptorConfig
function when removing the securityInterceptorService
dependency. So it seems the service is not registered. Checked all file paths, checked for spelling errors in the variable names, et cetera.
I'd appreciate if someone is able to point out the mistake I made.
------------------------ Update
The following function that is injected via .config()
does work however. Yet, when I try to push the securityInterceptor in this function, I get the same unknown provider error.
export default function config($logProvider, $locationProvider, toastr, $compileProvider) {
'ngInject';
// Enable log
$logProvider.debugEnabled(true);
// Set options third-party lib
toastr.options.timeOut = 3000;
toastr.options.positionClass = 'toast-top-right';
toastr.options.preventDuplicates = true;
toastr.options.progressBar = true;
// HTML 5 Modus Enabled No #
$locationProvider.html5Mode({
enabled: true,
requireBase: false,
hashPrefix: '!'
});
// Disable debug info
$compileProvider.debugInfoEnabled(true);
}
Upvotes: 1
Views: 938
Reputation: 925
Turns out dat you cannot inject services in the .config()
. It all works fine when changing index.interceptors.js
to this:
export default function interceptorConfig($httpProvider) {
'ngInject';
// Security interceptor
$httpProvider.interceptors.push('securityInterceptorService');
}
Upvotes: 1