Beginning AngularJS

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

We can’t place this code in the success method, because, if an error occurs, our form will be trapped in its
working state. This would lead to a somewhat conflicted user interface. We could put the code in both the success
and error methods, however. That would work, though a much better way is to use the promise object’s finally
method. This is a cleaner way to handle this kind of task, the kind of task you want performed regardless of whether or
not the promise was rejected or fulfilled.


■ Tip no matter the outcome of a promise, the finally method will always be called.


Handling Returned Data

It is common for asynchronous communications to be a little more involved than simply sending data on its way.
Some scenarios require us to process data with which the web server might respond. A username lookup service,
for example, might require us to inspect a returned value to see if a given username exists within the system. How
would we access this data? What about error handling? How do we find out if and what went wrong? We look at these
considerations next.


Accessing Returned Data

It might be a simple transaction identifier or a large data set containing some or all of a customer’s purchasing history;
it doesn’t really matter. Either way, this information, the server’s response, is represented by the data argument with
which we expect our success method’s callback function to be supplied. Listing 7-12 shows how we might go about
displaying a transaction number to our user.


Listing 7-12. Handling Request Data


promise.success(function (data, status) {


$scope.successMessage = "Your transaction identifier is " + data.transactionID;
$scope.showSuccessMessage = true;


});


Figure 7-3. Clicking on the Register button

Free download pdf