REST Services

Even tough you can access restful services with the $http-service, there’s the more convenient $resource-service we can leverage. It abstracts the low level of the $http-service. To be able to use it, we need to load the ngResource-module, which we can do by adding the scriptsource and adding the module as a dependency to the main-module. The following example demonstrates this:

Example

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular-resource.min.js"></script> 

<script type="text/javascript">
	var app = angular.module('app', ['ngResource']);
</script>

Play with example »

To be able to use the $resouce-service, we need to pass it to controller additionally to the $scope. The $resource-service can be called like a method, in which we pass a url and optionally parameters. It returns an object with methods to call on the rest-service. By default there are five methods available:

  • get (retrieve single record)
  • query (retrieve multiple records as array)
  • save (create/update record)
  • remove (delete record)
  • delete (delete record)

Please note, that you would encapsulate $resource-service method calls in a factory to make your code better read- and testable. For the sake of simplicity we won’t do this here. Note as well, that some of the examples in this tutorial, which calls create, update and delete, retrieve only mocked responses, meaning the changes are not really stored!

Loading multiple records
In our case we call the query-method to retrieve an array of records. At first it returns an empty reference-object, which is populated with the records, as soon as they are retrieved. See the beauty as we do not need any ugly callback-methods? In the following example we retrieve all posts from a RESTservice.

Example

app.controller('PostingsCtrl', ['$scope', '$resource', function($scope, $resource) {
	$scope.loadPosts = function() {
		// Note that the second parameter is an empty object, as we do not need to pass
		// any parameters.
		var postingsResource = $resource('http://jsonplaceholder.typicode.com/posts/', {});
		$scope.postings = postingsResource.query();
	};
}]);

Play with example »

Loading single record
Next we load a single post by passing the postid to the GET-call. This can be done by defining an url with parameters in the form of http://url/method/:yourparameter. Additionally we need to pass a value for this parameter as an object.

Example

$scope.loadPosts = function() {
	// GET-call to the url http://jsonplaceholder.typicode.com/posts/3
	var postingsResource = $resource('http://jsonplaceholder.typicode.com/posts/:postId', { postId: '3'});
	$scope.post = postingsResource.get();
};

Play with example »

Create new record
The first question is, how do we get a new record and what is our model? Well for this example we let AngularJS define our model ($scope.post) from the html-model. We use the following HTML for it:

<div ng-controller="PostingsCtrl">
	<p><label>Title</label> <input type="text" ng-model="post.title" /></p>
	<p><label>Body</label> <input type="text" ng-model="post.body" /></p>

	<button ng-click="createPost()">Create Post</button>
</div>

To create the record we use the resources save-method. It sends our post-model with a POST-request to the server.

Example

app.controller('PostingsCtrl', ['$scope', '$resource', function($scope, $resource) {
	var postingsResource = $resource('http://jsonplaceholder.typicode.com/posts/', {});

	$scope.createPost = function() {
	$scope.post = postingsResource.save($scope.post);
	};
}]);

Play with example »

Update a record
Updating a record is almost the same, as creating a new one. The only difference is, that we retrieve the existing record first. Our test-restservice needs to receive a PUT-message to do an update. As you’ve seen, there’s no default method, meaning we need to define our own update-method in the next example. We do this by passing a third parameter to the $resource-service, which defines a new update-action with the PUT-method.

Example

app.controller('PostingsCtrl', ['$scope', '$resource', function($scope, $resource) {
	var postingsResource = $resource('http://jsonplaceholder.typicode.com/posts/:postId',
				{ postId: '3'},
				{ 'update': { method:'PUT' }});
	$scope.post = postingsResource.get();

	$scope.updatePost = function() {
		postingsResource.update($scope.post);
	};
}]);

Play with example »

Delete a record
The last step to have all CRUD-methods in place is to call the delete-method. As with loading or updating you specify with the url which record to select and finish the operation by calling the delete-method on the $resource-service.

Example

app.controller('PostingsCtrl', ['$scope', '$resource', function($scope, $resource) {
	$scope.deletePost = function() {
		var postingsResource = $resource('http://jsonplaceholder.typicode.com/posts/:postId', { postId: '3'});
		postingsResource.delete();
	};
}]);

Play with example »

This tutorial should have given you a good overview. There are many more settings you can do on the $resource service, like caching, timeouts, promises etc.. I recommend you to visit the official AngularJS $resource reference. What you learned here should make it alot easyer to get started there.