how to emit an event in a callback using $resource in angularJS

57 views Asked by At

I have a function like this one:

module.exports.getMyItems = ['$rootScope', '$resource', function getMyItems($rootScope, $resource) {
  return $resource('/myEndpoint/:id',
    {id  : '@id'},
    {
      query: {
        method: 'GET',
        isArray: true
      }
  });
}];

I want to emit an event like

$rootScope.$emit('ITEMS_LOADING');

how can I add a callback to emit this event when the resource is loaded?

1

There are 1 answers

0
georgeawg On

how can I add a callback to emit this event when the resource is loaded?

One can add a response interceptor:

module.exports.getMyItems = ['$rootScope', '$resource', function getMyItems($rootScope, $resource) {
  return $resource('/myEndpoint/:id',
    {id  : '@id'},
    {
      query: {
        method: 'GET',
        isArray: true
      },
      interceptor: {
          response: function(response) {
            // Get the instance from the response object
            var instance = response.resource;
            //emit message
            $rootScope.$emit('ITEMS_LOADED');        
            // Return the instance
            return instance;
          }    
      }
  });
}];

For more information, see