AngularJS 中的 TypeScript 拦截器 [英] TypeScript interceptor in AngularJS
本文介绍了AngularJS 中的 TypeScript 拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用 TypeScript 在 AngularJS 中设置请求拦截器时遇到问题
I'm having problems setting up a request interceptor in AngularJS using TypeScript
以下代码段有效,不工作的变体被注释掉.无论我在构造函数中注入什么,局部变量都未在 request
方法中定义.
The following snippet works, not working variant is commented out. No matter what I inject in the constructor the local variables are undefined in the request
method.
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);
});
推荐答案
是因为this
错误.解决办法:
It is because of the wrong this
. Solution:
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;
}
要了解您为什么需要这个:https://www.youtube.com/watch?v=tvocUcbCupA&hd=1
To understand why you need this : https://www.youtube.com/watch?v=tvocUcbCupA&hd=1
这篇关于AngularJS 中的 TypeScript 拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文