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

后端 未结 9 1818
轮回少年
轮回少年 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:53

    To compelement the other fine answers regarding arrow functions, I think it's a bit cleaner using a static factory method in the Interceptor:

    export default class AuthenticationInterceptor {
     static $inject = ['$q', '$injector', '$rootRouter'];
     constructor ($q, $injector, $rootRouter) {
      this.$q = $q;
      this.$injector = $injector;
      this.$rootRouter = $rootRouter;
     }
    
     static create($q, $injector, $rootRouter) {
      return new AuthenticationInterceptor($q, $injector, $rootRouter);
     }
    
     responseError = (rejection) => {
      const HANDLE_CODES = [401, 403];
    
      if (HANDLE_CODES.includes(rejection.status)) {
       // lazy inject in order to avoid circular dependency for $http
       this.$injector.get('authenticationService').clearPrincipal();
       this.$rootRouter.navigate(['Login']);
      }
      return this.$q.reject(rejection);
     }
    }
    

    Usage:

    .config(['$provide', '$httpProvider', function ($provide, $httpProvider) {
    $provide.factory('reauthenticationInterceptor', AuthenticationInterceptor.create);
    $httpProvider.interceptors.push('reauthenticationInterceptor');
    }]);
    

提交回复
热议问题