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

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

    Note that using arrow functions in class properties is an experimental feature for ES7. However most transpilers don't have a problem with it.

    If you want to stick to the official ES6 implementation you can create instance methods instead of prototype methods by defining your methods in the constructor.

    class AuthenticationInterceptor {
      /* ngInject */
      constructor($q, $window) {
        
        this.responseError = (rejection) => {
          const authToken = rejection.config.headers.Authorization;
          if (rejection.status === 401 && !authToken) {
            const authentication_url = rejection.data.errors[0].data.authenticationUrl;
            $window.location.replace(authentication_url);
            return $q.defer(rejection);
          }
          return $q.reject(rejection);
        };
        
      }
    }

    I like this solution because it decreases the amount of boilerplate code;

    • You no longer have to put all your dependencies in this. So instead of using this.$q you can just use $q.
    • No need to return explicitly bound class methods from the constructor

    Having one extra level of indentation is a downside. Furthermore this method might not be suitable for classes that are instantiated a lot as it consumes more memory in that case. E.g.; Using direct class properties (transpiled to prototype methods) is more efficient for controllers of components that are likely to be used multiple times on one page. Don't worry about services, providers and factories as these are all singletons and they will only be instantiated once.

提交回复
热议问题