gpt4 book ai didi

angularjs - AngularJS 中的 TypeScript 拦截器

转载 作者:搜寻专家 更新时间:2023-10-30 20:32:33 25 4
gpt4 key购买 nike

我在使用 TypeScript 在 AngularJS 中设置请求拦截器时遇到问题

以下代码段有效,但注释掉了无效变体。无论我在构造函数中注入(inject)什么,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;
}

了解您为什么需要这个:https://www.youtube.com/watch?v=tvocUcbCupA&hd=1

关于angularjs - AngularJS 中的 TypeScript 拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23211692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com