我在使用TypeScript
在AngularJS中设置请求拦截器时遇到问题以下代码段有效,而非工作变量已被注释掉。无论我在构造函数中注入什么,request
方法中的局部变量都是未定义的。
module Services
{
export class AuthInterceptor
{
public static Factory(TokenService: Services.ITokenService)
{
return new AuthInterceptor(TokenService);
}
constructor(private TokenService: Services.ITokenService)
{
this.request = (config: ng.IRequestConfig) =>
{
config.headers = config.headers || {};
if(this.TokenService.IsAuthorised())
config.headers.Authorization = 'Bearer ' + this.TokenService.Token;
return config;
};
}
public request: (config: ng.IRequestConfig)=>ng.IRequestConfig;
/* THIS IS NOT WORKING
public request(config)
{
// this.TokenService is undefined here as well as $window or $q which I tried to inject
config.headers = config.headers || {};
if(this.TokenService.Token != "")
config.headers.Authorization = 'Bearer ' + this.TokenService.Token;
return config;
}
*/
}
}
angular.module("Services")
.config(($httpProvider: ng.IHttpProvider)=>
{
$httpProvider.interceptors.push(Services.AuthInterceptor.Factory);
});
答案 0 :(得分:30)
这是因为错误this
。解决方案:
public request = (config) =>
{
// this.TokenService is undefined here as well as $window or $q which I tried to inject
config.headers = config.headers || {};
if(this.TokenService.Token != "")
config.headers.Authorization = 'Bearer ' + this.TokenService.Token;
return config;
}