Communicating with a Back-end Server
}, {
update: {method:'PUT'}
});
Users.prototype.getFullName = function() {
return this.firstName + ' ' + this.lastName;
};
return Users;
})
Adding new methods on the class (constructor) level is also possible. Since,
in JavaScript a function is a first-class object, we can define new methods on a
constructor function. This way we can add custom methods "by hand" instead of
relying on the AngularJS automatic method generation. This might prove useful,
if we need some non-standard logic in one of the resources methods. For example,
the MongoLab's REST API requires that the identifier of an object is removed from a
payload while issuing PUT (update) requests.
$resource creates asynchronous methods
Let's have a second look at the query method example:
$scope.users = Users.query();
We might get the impression that generated resources behave in the synchronous
way (we are not using any callbacks or promises here). In reality the query
method call is asynchronous and AngularJS uses a smart trick to make it looks
like synchronous.
What is going on here is that AngularJS will return immediately from a call to
Users.query()with an empty array as a result. Then, when the asynchronous
call is successful, and real data arrives from the server, the array will get updated
with the data. AngularJS will simply keep a reference to an array returned at first,
and will fill it in when data is available. This trick works in AngularJS since upon
data arrival the content of the returned array will change and templates will get
refreshed automatically.
But don't get mistaken, the $resource calls are asynchronous. This is often a source
of confusion, as you might want to try to write the following code (or access the
initial array in any other way):
$scope.users = Users.query();
console.log($scope.users.length);
And it doesn't work as expected!