Mastering Web Application

(Rick Simeone) #1

Communicating with a Back-end Server


.factory('Users', function (mongolabResource) {
return mongolabResource('users');
})

.controller('CustomResourceCtrl', function ($scope, Users,
Projects) {

Users.query().then(function(users){
$scope.users = users;
});
});

The usage of our custom resource doesn't differ much from the original $resource
equivalent. To start with we need to declare a dependency on the module where a
custom resource factory is defined (mongolabResource). Next, we need to provide
required configuration options in form of a constant. As soon as the initial setup
is done we can define actual resources created by a custom factory. It is as easy as
invoking the mongolabResource factory function and passing a MongoDB collection
name as an argument.


During application's run-time a newly defined resource constructor (here: Users)
can be injected as any other dependency. Then an injected constructor can be used
to invoke either class-level or instance-level methods. An example of the later is
shown here:


$scope.addSuperhero = function () {
new Users({name: 'Superhero'}).$save();
};

The best part of switching to a custom, $http-based version of a resource factory is
that we can enjoy the full power of the Promise API.


Using advanced features of $http


The $http service is extremely flexible and powerful. Its super-powers are result of
clean, flexible API and usage of the Promise API. In this section, we are going to see
how we can use some of the more advanced features of the $http service.


Intercepting responses


AngularJS built-in $http service allows us to register interceptors that will be
executed around each and every request. Such interceptors are very useful in
situations where we need to do special processing for many (potentially all) requests.

Free download pdf