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

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

    My working solution without using ngInject

    myInterceptor.js

    export default ($q) => {
    let response = (res) => {
        return res || $q.when(res);
    }
    
    let responseError = (rejection) => {
        //do your stuff HERE!!
        return $q.reject(rejection);
    }
    
    return {
        response: response,
        responseError: responseError
    }
    

    }

    myAngularApp.js

    // angular services
    import myInterceptor from 'myInterceptor';
    
    // declare app
    const application = angular.module('myApp', [])
            .factory('$myInterceptor', myInterceptor)
            .config(['$httpProvider', function($httpProvider) {  
               $httpProvider.interceptors.push('$myInterceptor');
            }]);
    

提交回复
热议问题