I am building and AngularJS app using ES6 classes with traceur transpiling to ES5 in AMD format.
in my module I import the interceptor class and register it as a service
Note that using arrow functions in class properties is an experimental feature for ES7. However most transpilers don't have a problem with it.
If you want to stick to the official ES6 implementation you can create instance methods instead of prototype methods by defining your methods in the constructor.
class AuthenticationInterceptor {
/* ngInject */
constructor($q, $window) {
this.responseError = (rejection) => {
const authToken = rejection.config.headers.Authorization;
if (rejection.status === 401 && !authToken) {
const authentication_url = rejection.data.errors[0].data.authenticationUrl;
$window.location.replace(authentication_url);
return $q.defer(rejection);
}
return $q.reject(rejection);
};
}
}
I like this solution because it decreases the amount of boilerplate code;
this
. So instead of using this.$q
you can just use $q
. Having one extra level of indentation is a downside. Furthermore this method might not be suitable for classes that are instantiated a lot as it consumes more memory in that case. E.g.; Using direct class properties (transpiled to prototype methods) is more efficient for controllers of components that are likely to be used multiple times on one page. Don't worry about services, providers and factories as these are all singletons and they will only be instantiated once.