pethel
pethel

Reputation: 5537

How to create a service/factory angularjs

I have this call. I would like to manipulate the data returned by the REST service before the controller uses it. How can this be accomplished? Now I get the raw data. I understand that I can but this logic ApiFactory.get(function(data)); but I prefer to have the logic in the server. How can I do this?

In Service:

app.factory('ApiFactory', ['$resource', function($resource) {
  return $resource('http://localhost:8080/rest/forum/categories/1');
}]);

In controller:

app.controller('SubjectCntrl', ['$scope', 'categoryService', 'ApiFactory', function($scope, categoryService, ApiFactory) {
    ApiFactory.get(function(data) {
        console.log(data);
    });
}]);

Upvotes: 0

Views: 69

Answers (1)

D.Evangelista
D.Evangelista

Reputation: 6541

You can create another factory that parses the data as you want. Something like that:

app.factory('ApiFactory', ['$resource', function($resource) {
    return $resource('http://localhost:8080/rest/forum/categories/1');
}]);

app.factory('ApiParser', ['ApiFactory', function(ApiFactory) {
    return {
        get: function() {
            var data = ApiFactory.get(function(d) {
                /* do whatever you need to do with the data */
                return parsedData;
            });
            return data;
        }
    }
}]);

app.controller('SubjectCntrl', ['$scope', 'categoryService', 'ApiParser', function($scope, categoryService, ApiParser) {
    $scope.parsedData = ApiParser.get();
}]);

Upvotes: 1

Related Questions