Guyute
Guyute

Reputation: 149

Using Angular $Resource what is the angular way to create a service using multiple api calls?

I am working on an angular project and I am using $ resource for the first time. I currently have just as a test to get data out of my database a service that has one call to $resource

Here is my service:

(function() {
"use strict";
angular.module("commonServices")
    .factory("ptaResource",
    ["$resource", ptaResource]);

function ptaResource($resource) {
    return $resource("http://localhost:55928/api/excercises", {}, { 'query': { method: 'GET', isArray: true } });
}
})();

My question is this. I have a lot of calls to make to various controllers and methods within those controllers. I cant wrap my head around how to structure a service that allows me to call it with an endpoint listed

I tried doing something like this:

var services =[
    getExercises: getExercises,
    doSomething: doSomething
   ];
   return service;

    function getExercises (){
        return $resource request here
      }

But that did not work, I have looked on line but any tutorial is only exposing one of each type of request. I am going to have several get requests to controllers, some with different query strings. I will be querying different controllers as well. The purist in me tells me that all of this belongs in one place.

What would be a good method for doing this one large service with a way to call each request individually. Should I break them into a service per web api controller. Any input would be appreciated.

Thanks, John

Upvotes: 0

Views: 41

Answers (1)

Brian Lewis
Brian Lewis

Reputation: 5729

If you wanted to wrap your resources in a service, you could do something like this:

angular
    .module('commonServices', ['ngResource'])
    .factory('ptaResource', ['$resource', function($resource) {
        return $resource('http://localhost:55928/api/excercises/:excerciseId', {
            excerciseId: '@id'
        });
    }])
    .service('CommonService', ['ptaResource', function(ptaResource) {
        return {
            getExercises: function() {
                return ptaResource.query().$promise;
            }
        };
    }]);

Then you could call it like so:

angular
    .module('app', ['commonServices'])
    .controller('SomeController', ['$scope', 'CommonService', function($scope, CommonService) {
        $scope.exercises = CommonService.getExercises();

        // or
        CommonService.getExercises().then(function(exercises) {
            $scope.exercises = exercises;
        }).catch(function(err) {
            // handle error here
        });
    }]);

Upvotes: 1

Related Questions