Search code examples
angularjsangular-resource

AngularJS: Resource factory and callback function


Hi being new to Angular i'm having difficulty seeing how to handle data when using $resource in a factory. I'm trying to move from $http requests to $resources in my factory.

First i had (simplified code):

.factory('MetadataService', function($http) {
      $http({
            method: 'OPTIONS',
            url: 'http://myurl'
      }).success(function(data) {
         customized_data = do_some_complex_handling_on_data(data)
         callback(customized_data);
         });
});

When i try to use a $resource in my factory, it seems that i have to call the do_some_complex_handling_on_data() method in my controller:

.factory('MetadataService', function($resource) {
   return($resource('http://myurl', {}, {
        metadata: {method: 'OPTIONS'}
   }));
});

# controller:

var metadata = do_some_complex_handling_on_data(MetadataService.metadata());

Since i'm gonna use the factory in a lot of controllers for different sections in my application (that's why i made a factory in the first place), i would like to have my factory return the data as i need it. And not have to customize the data after the factory returns it.

question: How do i let my factory call the do_some_complex_handling_on_data() function instead of the controller?


Solution

  • You can use response transformer that $http service provides. A transformer is used to transform the response of $http before it is delivered to the end client.

    By default there is a single transformer register that convert json string to json object. You can append your own transformer to this collection and it will be called with the response json object. In your transformer function you can then call any function you want that can transform the data.

    metadata: {
       method: 'OPTIONS'
       transformResponse: appendTransform($http.defaults.transformResponse,   
            function(value) {
                return do_some_complex_handling_on_data(value);
            })
    }
    
    function appendTransform(defaults, transform) {
    
      // We can't guarantee that the default transformation is an array
      defaults = angular.isArray(defaults) ? defaults : [defaults];
    
      // Append the new transformation to the defaults
      return defaults.concat(transform);
    }
    

    I have taken this code from the docs here

    Also read documentation on "Default Transformations" in $http service