angularjs http interceptor class (ES6) loses binding to 'this'

后端 未结 9 1653
轮回少年
轮回少年 2021-02-05 11:14

I am building and AngularJS app using ES6 classes with traceur transpiling to ES5 in AMD format.

in my module I import the interceptor class and register it as a service

9条回答
  •  长情又很酷
    2021-02-05 11:58

    Working solution with arrow functions:

    var AuthInterceptor = ($q, $injector, $log) => {
        'ngInject';
    
        var requestErrorCallback = request => {
            if (request.status === 500) {
              $log.debug('Something went wrong.');
            }
            return $q.reject(request);
        };
    
        var requestCallback = config => {
            const token = localStorage.getItem('jwt');
    
            if (token) {
                config.headers.Authorization = 'Bearer ' + token;
            }
            return config;
        };
    
        var responseErrorCallback = response => {
             // handle the case where the user is not authenticated
            if (response.status === 401 || response.status === 403) {
                // $rootScope.$broadcast('unauthenticated', response);
                $injector.get('$state').go('login');
           }
           return $q.reject(response);
        }
    
      return {
        'request':       requestCallback,
        'response':      config => config,
        'requestError':  requestErrorCallback,
        'responseError': responseErrorCallback,
      };
    };
    
    /***/
    var config = function($httpProvider) {
        $httpProvider.interceptors.push('authInterceptor');
    };
    
    /***/    
    export
    default angular.module('services.auth', [])
        .service('authInterceptor', AuthInterceptor)
        .config(config)
        .name;
    

提交回复
热议问题