Mastering Web Application

(Rick Simeone) #1

Communicating with a Back-end Server


The $timeout service returns a promise that will be resolved with
a value returned from a timeout callback.

As convenient as it might be this pattern results in code that is not very readable.
Things can get even more confusing when we realize that promises returned from a
function call are not rendered automatically! The template markup is as follows:


<h1>Hello, {{getName()}}!</h1>

And the following code in a controller:


$scope.getName = function () {
return $timeout(function () {
return "World";
}, 2000);
};

This code won't yield the expected text in a template.


We advise against exposing promises directly on a $scope and
relying on the automatic rendering of resolved values. We find
this approach is rather confusing, especially taking into account
inconsistent behavior for promises returned from a function call.

The promise API with $http


Now that we've covered promises we can demystify the response object being
returned from the $http method calls. If you recall a simple example from the
beginning of this chapter you will remember that $http calls return an object on
which the success and error callbacks can be registered. In reality the returned object
is a fully fledged promise with two additional, convenience methods: success and
error. As any promise, the one returned from a $http call has also the then method
which allows us to rewrite the callback registration code in the following form:


var responsePromise = $http.get('data.json');
responsePromise.then(function (response) {
$scope.data = response.data;
},function (response) {
throw new Error('Something went wrong...');
});

Promises returned from the $http services are resolved with the response object
which has the following properties: data, status, headers and config.

Free download pdf