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

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

    This is exactly the same problem I'm experiencing, however, I found a workaround by setting the 'this' in a self variable just like solving the scoping issue on es5, and it works fine:

    let self;
    
    class AuthInterceptor{
    
       constructor(session){
           self = this;
           this.session = session;
       }
    
       request(config){
           if(self.session) {
               config.headers = self.session.getSessionParams().headers; 
           }
           return config;
       }
    
       responseError(rejection){
           if(rejection.status == 401){
    
           }
    
           return rejection;
       }
    
    }
    
    export default AuthInterceptor;
    

提交回复
热议问题