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

后端 未结 9 1626
轮回少年
轮回少年 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 12:07

    Look at these lines of source code:

    // apply interceptors
    forEach(reversedInterceptors, function(interceptor) {
        if (interceptor.request || interceptor.requestError) {
            chain.unshift(interceptor.request, interceptor.requestError);
        }
        if (interceptor.response || interceptor.responseError) {
            chain.push(interceptor.response, interceptor.responseError);
        }
    });
    

    When interceptor.responseError method is pushed into chain it looses its context (just function is pushed, without any context);

    Later here it will be added to promise as reject callback:

    while (chain.length) {
        var thenFn = chain.shift();
        var rejectFn = chain.shift();
    
        promise = promise.then(thenFn, rejectFn);
    }
    

    So if promise will be rejected, rejectFn(your responseError function) will be executed as an ordinary function. In this case this references to window if script is being executed in non-strict mode, or equals null otherwise.

    IMHO Angular 1 was written with ES5 consideration, so I think using it with ES6 is not a good idea.

提交回复
热议问题