Should all RESTful API calls be defined in the angular service?

I would name the following api routes

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

Will they all be defined in one angular service? And how would I do that? every tutorial that I looked at has a service in which it immediately returns a resource, and this is usually also for CRUD operations. Most likely, I will call these routes in several controllers, so I think that having it in one service is beneficial. Can someone show an example of how to create a service to call these routes?

I would like to do such operations 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 the function that makes the HTTP request for / api / user / inbox

+5
source share
1 answer

Yes, including all RESTfull API calls in a service is ideal. Benefits include:

  • URLs in one place, so when you change the API (or using a different version), you change it in one place.
  • It’s easy to reorganize an alternative to $ http, for example: restangular.
  • It is easy to add general error handling for queries, since all queries are in one place.
  • Ease of testing. 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 consume the real RESTfull API, I suggest you consider Restangular .

+4
source

All Articles