Write http interceptor as class

后端 未结 5 2068
情深已故
情深已故 2020-12-15 11:49

I\'m having trouble writing an angular http interceptor in plain TypeScript. The code I\'m trying to convert is the following:

.config([\'$httpProvider\', fu         


        
5条回答
  •  囚心锁ツ
    2020-12-15 11:56

    The config settings are as follows

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

    and your actual class should look as follows

    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);
        }
    }
    

提交回复
热议问题