javascript – 将http拦截器编写为类

前端之家收集整理的这篇文章主要介绍了javascript – 将http拦截器编写为类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我无法在普通的TypeScript中编写一个有角度的http拦截器.我要转换的代码如下:
.config(['$httpProvider',function ($httpProvider) {

    var interceptor = ['$rootScope','$q','httpBuffer',function ($rootScope,$q,httpBuffer) {
        function success(response) {
            return response;
        }

        function error(response) {
            if (response.status === 401 && !response.config.ignoreAuthModule) {
                var deferred = $q.defer();
                httpBuffer.append(response.config,deferred);
                $rootScope.$broadcast('event:auth-loginrequired',response);
                return deferred.promise;
            }
            // otherwise,default behavIoUr
            return $q.reject(response);
        }

        return function (promise) {
            return promise.then(success,error);
        };

    }];
    $httpProvider.responseInterceptors.push(interceptor);
}])

第一部分是清楚的,写一个构造函数的类,它接受三个依赖项$rootScope,$q和httpBuffer.还写两个私有方法成功和响应.

class MyInterceptorClass {
    constructor(private $rootScope: ng.IRootScopeService,private $q: ng.IQService,private httpBuffer: HttpBuffer) {
    }

    private success(response: ng.IHttpPromiseCallbackArg<any>): ng.IHttpPromiseCallbackArg<any> {
        return response;
    }

    private error(response: ng.IHttpPromiseCallbackArg<any>): ng.IHttpPromiseCallbackArg<any> {
        if (response.status == 401 && !((<any>response.config).ignoreAuthModule)) {
            var deferred = this.$q.defer();
            this.httpBuffer.append(response.config,deferred);
            this.$rootScope.$broadcast('event:auth-loginrequired',response);

            return deferred.promise;
        }

        // Otherwise,default behavior
        return this.$q.reject(response);
    }
}

拦截器的注册也应该是明确的:

.config(['$httpProvider',($httpProvider: ng.IHttpProvider)=> {
    $httpProvider.responseInterceptors.push(['$rootScope',MyInterceptorClass]);
}]);

我有麻烦的是原始JavaScript的最后一部分,匿名函数的返回值.如何在TypeScript中创建这个?据我所知,这在TypeScript中将是一个无名的方法,但这是不可能的.

解决方法

配置设置如下
.config(['$httpProvider',function ($httpProvider: ng.IHttpProvider) {
        $httpProvider.interceptors.push(AuthenticationInterceptor.Factory);
    }])

你的实际课程应该如下

module Common.Security {
'use strict';

export class AuthenticationInterceptor {

    public static Factory($q: ng.IQService) {
        return new AuthenticationInterceptor($q);
    }

    constructor(private $q: ng.IQService) {
    }

    //Method name should be exactly "response" - http://docs.angularjs.org/api/ng/service/$http
    public response(response) {
        console.log(response);
        return response || this.$q.when(response);
    }

    public responseError(rejection) {
        console.log(rejection.status);
        if (rejection.status === 401) {
        }
        // Otherwise,default behavior
        return this.$q.reject(rejection);
    }
}

猜你在找的JavaScript相关文章