Communicating with a Back-end Server
apiKey:'4fb51e55e4b02e56a67b0b66',
id:'@_id.$oid'
});
})
We start by registering a recipe (a factory) for the User constructor function. But
notice that we don't need to write any code for this constructor function. It is the
$resource service that will prepare implementation for us.
The $resource service will generate a set of methods that make it easy to interact
with a RESTFul endpoint. For example, querying for all the users in the persistence
store is as simple as writing:
.controller('ResourceCtrl', function($scope, Users){
$scope.users = Users.query();
});
What will happen upon the call to the User.query() method is that $resource
generated code is going to prepare and issue an $http call. When a response is
ready the incoming JSON string will get converted to a JavaScript array where each
element of this array is of type Users.
Calls to the $resource service return a generated constructor function
augmented with methods to interact with a RESTful endpoint: query,
get, save and delete.
AngularJS requires very little information to generate a fully functional resource.
Let's examine the parameters of the $resource method to see what input is required
and what can be customized:
$resource('https://api.mongolab.com/api/1/databases/ascrum/
collections/users/:id', {
apiKey:'4fb51e55e4b02e56a67b0b66',
id:'@_id.$oid'
});
The first argument is a URL or rather a URL pattern. The URL pattern can contain
named placeholders starting with the colon character. We can specify only one URL
pattern which means that all HTTP verbs should use very similar URLs.
If your back-end uses a port number as part of the URL, the port
number needs to be escaped while supplying the URL pattern to the
$resource call (For example, http://example.com\\:3000/api).
This is required since a colon has a special meaning in the $resource's
URL pattern.