Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should ALL RESTful API calls be defined in an angular service?

I would like to call the following api routes

/api/user/:id
/api/user/inbox
/api/user/blah

Would all of these be defined in one angular service? And how would I do that? every tutorial I've looked at has a service where it immediately returns the resource and it's usually for CRUD operations too. I'd most likely be calling these routes in multiple controllers so I think having it in one service is beneficial. Could someone show an example of how I would create a service to call these routes?

I'd like to do operations like this in other controllers

$scope.inbox = $api.getUserInbox()  //function which requests api/user/inbox

$scope.user = $api.getUser()   //function which requests api/user/:id

$scope.blah = $api.getUserBlah() //function which requests api/user/blah

where $api is the service I would define and getuserInbox() is a function which makes an http request for /api/user/inbox

like image 830
jory Avatar asked Jul 27 '16 01:07

jory


People also ask

Which AngularJS service allows interacting with a RESTful backend?

AngularJS's $resource service is easier to use than $http for interacting with data sources exposed as RESTful resources.


1 Answers

Yes, putting all RESTfull API calls into a service is ideal. Benefits include:

  • URLs in single place so when changing API (or using different version), you change it in single place.
  • Can easily refactor to use alternate to $http eg: restangular.
  • Easily add generic error handling for requests, since all requests in single place.
  • Makes testing easier. Just 'mock' your API service instead of messing with $httpBackend


app.service('userAPI', function($http) {
    var self = this;
    var baseUrl = "api/user/";

    self.getUser(id) {
        return $http.get(baseUrl + id);
    }
});

app.controller('myController', function($scope, userAPI) {
    userAPI.getUser(1).then(function(response) {
        $scope.user = response.data;
    };
}

PS - If you are consuming a true RESTfull API, I suggest you consider Restangular.

like image 171
Ben George Avatar answered Oct 18 '22 02:10

Ben George