加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS中的TypeScript拦截器

发布时间:2020-12-17 07:41:46 所属栏目:安全 来源:网络整理
导读:我在使用TypeScript在AngularJS中设置请求拦截器时遇到问题 以下代码段的作品,不工作的变体被注释掉.无论在构造函数中注入什么,请求方法中的局部变量都是未定义的. module Services{ export class AuthInterceptor { public static Factory(TokenService: Se
我在使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读