AngularJS中的TypeScript拦截器

时间:2014-04-22 06:09:43

标签: angularjs typescript this

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

1 个答案:

答案 0 :(得分:30)

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