AngularJS: transform response in $resource using a custom service
Asked Answered
P

2

11

I am trying to decorate the returned data from a angular $resource with data from a custom service. My code is:

angular.module('yoApp')
  .service('ServerStatus', ['$resource', 'ServerConfig', function($resource, ServerConfig) {
    var mixinConfig = function(data, ServerConfig) {
      for ( var i = 0; i < data.servers.length; i++) {
        var cfg = ServerConfig.get({server: data.servers[i].name});
        if (cfg) {
          data.servers[i].cfg = cfg;
        }
      }
      return data;
    };

    return $resource('/service/server/:server', {server: '@server'}, {
      query: {
        method: 'GET',
        isArray: true,
        transformResponse: function(data, header) {
          return mixinConfig(angular.fromJson(data), ServerConfig);
        }
      },
      get: {
        method: 'GET',
        isArray: false,
        transformResponse: function(data, header) {
          var cfg = ServerConfig.get({server: 'localhost'});
          return mixinConfig(angular.fromJson(data), ServerConfig);
        }
      }
  });
}]);

It seems I am doing something wrong concerning dependency injection. The data returned from the ServerConfig.get() is marked as unresolved. I got this working in a controller where I do the transformation with

ServerStatus.get(function(data) {$scope.mixinConfig(data);});

But I would rather do the decoration in the service. How can I make this work?

Pinkster answered 21/2, 2014 at 7:18 Comment(2)
Does the transformResponse function get called? What version of Angular are you using? You'll find a minimalistic example implementing response decoration here: jsfiddle.net/YxTNL/1Sarmatia
@LukasBünger Thanks for your reply. I figured out a solution and posted it to jsfiddle.net/maddin/7zgz6 What I wantet to achieve is not possible in transformResponse. I guess I write a proper answer...Pinkster
P
8

It is not possible to use the transformResponse to decorate the data with data from an asynchronous service. I posted the solution to http://jsfiddle.net/maddin/7zgz6/.

Here is the pseudo-code explaining the solution:

angular.module('myApp').service('MyService', function($q, $resource) {
  var getResult = function() {
    var fullResult = $q.defer();
    $resource('url').get().$promise.then(function(data) {
      var partialPromises = [];
      for (var i = 0; i < data.elements.length; i++) {
        var ires = $q.defer();
        partialPromisses.push(ires);
        $resource('url2').get().$promise.then(function(data2) {
          //do whatever you want with data
          ires.resolve(data2);
        });
        $q.all(partialPromisses).then(function() {
          fullResult.resolve(data);
        });
        return fullResult.promise; // or just fullResult
      }
    });
  };
  return {
    getResult: getResult
  };
});
Pinkster answered 26/2, 2014 at 11:50 Comment(0)
I
7

Well, Its actually possible to decorate the data for a resource asynchronously but not with the transformResponse method. An interceptor should be used.

Here's a quick sample.

angular.module('app').factory('myResource', function ($resource, $http) {
  return $resource('api/myresource', {}, {
    get: {
      method: 'GET',
      interceptor: {
        response: function (response) {
          var originalData = response.data;
          return $http({
              method: 'GET',
              url: 'api/otherresource'
            })
            .then(function (response) {
              //modify the data of myResource with the data from the second request
              originalData.otherResource = response.data;
              return originalData;
            });
        }
      }
    });

You can use any service/resource instead of $http.

Update:
Due to the way angular's $resource interceptor is implemented the code above will only decorate the data returned by the $promise and in a way breaks some of the $resource concepts, this in particular.

var myObject = myResource.get(myId);

Only this will work.

var myObject;
myResource.get(myId).$promise.then(function (res) {
  myObject = res;
});
Inimical answered 4/9, 2014 at 9:6 Comment(1)
"breaks some of the $resource concepts" too bad! $resource kind of sucks. Thanks for the helpful information, though!Homey

© 2022 - 2024 — McMap. All rights reserved.