AngularJS中的TypeScript拦截器

Max*_*kiy 13 this 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);
    });
Run Code Online (Sandbox Code Playgroud)

bas*_*rat 31

这是因为错误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;
    }
Run Code Online (Sandbox Code Playgroud)

要了解您需要的原因:https://www.youtube.com/watch?v = tvocUcbCupA&hd = 1