我正在研究this authorization code。 可以通过从以下行开始找到原始代码段:
为此,请添加名为“authInterceptorService.js”的新文件 “services”文件夹并粘贴以下代码:
这是javascript版本:
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;
}]);
这是TypeScript版本:
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);
}
在上面的注释中提到的TypeScript版本代码段:
var self = this;// "this" REFERENCES TO WINDOW INSTEAD OF AuthInterceptorService CLASS
我应该怎样做才能成功拨打self.$location.path('/login');
目前我收到Cannot read property 'path' of undefined
错误
答案 0 :(得分:1)
根据函数的调用方式,上下文可能会丢失。与标准Javascript中的情况一样,尽管一些Typescripts抽象使得它变得更容易。因此,看到使用AuthInterceptorService的另一端会有所帮助。
确保上下文保持的一种方法是使用Typescript的箭头函数。
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);
}
(来源:https://github.com/Microsoft/TypeScript/wiki/'此' -in-TypeScript#user-content-use-instance-functions)
请记住,虽然这解决了一些问题,但它也有缺点,并且不适用于所有情况 - 上述消息来源列出了其中的一些。