Chapter 3
Fortunately it is possible to use callbacks in the methods generated by the $resource
factory and rewrite the preceding code to make it behave as intended:
Users.query(function(users){
$scope.users = users;
console.log($scope.users.length);
});
Methods generated by the $resource factory are asynchronous, even
if AngularJS is using a clever trick, and the syntax might suggest that
we are dealing with the synchronous methods.
Limitations of the $resource service
The $resource factory is a handy service, and lets us to start talking to RESTful
back-ends in virtually no time. But the problem with $resource is that it is a
generic service; not tailored to any particular back-end needs. As such it takes some
assumptions that might not be true for the back-end of our choice.
If the $resource factory works for your back-end and web-application, that's
great. There are many use-cases where $resource might be enough, but for more
sophisticated applications it is often better to use lower-level $http service.
Custom REST adapters with $http
The $resource factory is very handy, but if you hit its limitations it is relatively easy
to create a custom, $resource-like factory based on the $http service. By taking
time to write a custom resource factory we can gain full control over URLs and data
pre/post processing. As a bonus we would no longer need to include the angular-
resource.js file and thus save few KB of the total page weight.
What follows is a simplified example of a custom resource-like factory dedicated
to the MongoLab RESTful API. Familiarity with the Promise API is the key to
understanding this implementation:
angular.module('mongolabResource', [])
.factory('mongolabResource', function ($http, MONGOLAB_CONFIG) {
return function (collectionName) {
//basic configuration
var collectionUrl =
'https://api.mongolab.com/api/1/databases/' +
MONGOLAB_CONFIG.DB_NAME +