AngularJS中的TypeScript拦截器

前端之家收集整理的这篇文章主要介绍了AngularJS中的TypeScript拦截器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在使用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);
    });
这是因为这是错误的.解:
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

原文链接:https://www.f2er.com/angularjs/142819.html

猜你在找的Angularjs相关文章