I am working on this authorization code. Original code snippet can be found by starting from line:
To do so add new file named “authInterceptorService.js” under “services” folder and paste the code below:
This is javascript version:
angular.module('eucngts').factory('AuthInterceptorService', ['$q', '$location', function ($q, $location) {
var authInterceptorServiceFactory = {};
var _responseError = function (rejection) {
if (rejection.status === 401) {
localStorage.removeItem('authorizationData');
$location.path('/login');
}
return $q.reject(rejection);
}
authInterceptorServiceFactory.responseError = _responseError;
return authInterceptorServiceFactory;
}]);
And this is TypeScript version:
module Services {
export class AuthInterceptorService {
$location: ng.ILocationService;
$q: ng.IQService;
constructor($location, $q) {
var self = this;
self.$location = $location;
self.$q = $q;
}
public responseError(rejection) {
var self = this;// "this" REFERENCES TO WINDOW INSTEAD OF AuthInterceptorService CLASS
if (rejection.status === 401) {
localStorage.removeItem('authorizationData');
self.$location.path('/login');
}
return self.$q.reject(rejection);
}
static AuthInterceptorServiceFactory($location, $q) {
return new AuthInterceptorService($location, $q);
}
}
AuthInterceptorService.$inject = ['$location', '$q'];
angular.module('eucngts').factory('AuthInterceptorService', AuthInterceptorService.AuthInterceptorServiceFactory);
}
In TypeScript version as mentioned in comment above code snippet:
var self = this;// "this" REFERENCES TO WINDOW INSTEAD OF AuthInterceptorService CLASS
What should I do that I can successfully call self.$location.path('/login');
At the moment I receive Cannot read property 'path' of undefined error
AuthInterceptorServicewould help. One way to ensure that the context stays is to use Typescript's arrow functions. Something likepublic responseError = (rejection) => {...}(Source: github.com/Microsoft/TypeScript/wiki/… )