Beginning AngularJS

(WallPaper) #1
Chapter 7 ■ ServiCeS and Server CommuniCation

Let’s take the $http service and use it within our own service, a service we will call memberDataStoreService.
We will use this new service to handle our registration form data, but this service could go on to perform other
membership-related tasks, such as handling logins and the ability to change passwords. We will keep it simple here,
though, and focus only on the registration. Take a look at Listing 7-6.


Listing 7-6. The memberDataStoreService Service


var module = angular.module('myapp', []);


module.factory('memberDataStoreService', function ($http) {


var memberDataStore = {};


memberDataStore.doRegistration = function (theData) {
var promise = $http({method: 'POST', url: 'memberservices/register', data: theData});
return promise;
}


return memberDataStore;


});


There are a few things to note about Listing 7-6. We register our service using the name memberDataStoreService,
and we make sure that our factory function has access to the $http service. Next, we create a memberDataStore object.
This is to be the return value of our factory function and the object to which we can attach all of our service methods.
As previously mentioned, we will limit it to just the one here, the doRegistration() method.
The doRegistration() method has just one argument: the data required to perform a registration. This is
the data that is collected from the user via the registration form. Here’s the interesting part: this method returns
the promise object that was created by the call to the $http service. We very much want our service to take care of
the connection to the web server and data transmission, but we very much do not want it poking its nose into our
user-interface concerns. Using a promise, as you will see next, we can manipulate the user interface from within our
controller code instead.
We are now ready to look at a more complete code listing. Listing 7-7 is a reworking of the registration form we
built in the last chapter. This time, it makes use of our memberDataStoreService.


Table 7-1. The Arguments Provided to the Success and Error Functions


Name Type Description


data string|Object The response body transformed with the transform functions


status number HTTP status code of the response


headers function([headerName]) Header getter function


config Object The configuration object that was used to generate the request


statusText string HTTP status text of the response

Free download pdf