Search code examples
angularjsangular-resource

How to do Dependency Injection of a service into an interceptor, using $resource


I tried the following:

$resource(ur'stuff/:thingId',
  {
    someMethod:{
      method: 'GET',
      interceptor: ['OtherService', function(Otherservice){
         console.log('Too bad, not executed...');
         return {
          response: (response) => {
            console.log('Too bad, not executed...');
          }
        }
      }]

    }
  }

)

But it does not work. I found some mentions that $resource has particularities compared to $http, but I could not find the right pattern for this.


Solution

  • You can not directly inject service with interceptor, instead you should be wrapping $resource in factory or service and then can use factory dependency into $resource.interceptor to use.

    Example is attached below:

    angular.module('mainModule', ['ngResource']).
    factory("MyResource", ['$resource', 'SomeService', function ($resource, SomeService) {
        return $resource(
            '/', {
            someMethod: {
                method: 'GET',
                interceptor: {
                    response: function (data) {
                        // here you can use SomeService
                        console.log('response in interceptor', data);
                    },
                    responseError: function (data) {
                        // here you can use SomeService
                        console.log('error in interceptor', data);
                    }
                }
            }
        }
    
        );
    }]);
    

    Way to import service in ES6 way:

    import mainModule from './mainModule';
    
    class SomeController {
        constructor($scope, SomeService) {
            this.$scope = $scope;
            this.SomeService= SomeService;
        }
    }
    
    SomeController.$inject = ['$scope', 'SomeService'];
    
    mainModule.controller('SomeController', SomeController);
    

    In similar fashion you can make factories and services as well.