AngularJS中的TypeScript拦截器

我在使用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);

});

回答:

是因为错误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;

}

以上是 AngularJS中的TypeScript拦截器 的全部内容, 来源链接: utcz.com/qa/405617.html

回到顶部