我在使用TypeScript在AngularJS中设置请求拦截器时遇到问题
以下代码段的作品,不工作的变体被注释掉.无论在构造函数中注入什么,请求方法中的局部变量都是未定义的.
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); });
这是因为这是错误的.解:
原文链接:https://www.f2er.com/angularjs/142819.htmlpublic 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; }