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

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

    To add to the conversation, you could return an object from the constructor that contains explicitly bound class methods.

    export default class HttpInterceptor {
    
       constructor($q, $injector) {
           this.$q = $q;
           this.$injector = $injector;
    
           return {
               request: this.request.bind(this),
               requestError: this.requestError.bind(this),
               response: this.response.bind(this),
               responseError: this.responseError.bind(this)
           }
       }
    
       request(req) {
           this.otherMethod();
           // ...
       }
    
       requestError(err) {
           // ...
       }
    
       response(res) {
           // ...
       }
    
       responseError(err) {
           // ...
       }
    
       otherMethod() {
           // ...
       }
    
    }
    

提交回复
热议问题