Using the $q Service to Provide Deferred Responses

An extremely useful service provided by AngularJS is the $q service. The $q service is a promise/deferred response implementation. Since not all services can respond immediately to a request, there is a need to defer the response until the service is ready to respond. That is where the $q service comes in. The idea is that you can make a request, and rather than getting the response directly, you will get a promise that the service will respond. The requesting application can then assign a callback function that should be executed when the deferred request completes successfully or fails.

To utilize the $q service for deferred responses, you will first need to create a deferred object using the following syntax:

var deferred = $q.defer();

After you have a deferred object, you can pass the promise around by accessing the promise attribute. For example, the following line returns the promise to the calling application:

function makeDeferredRequest(){
  var deferred = $q.defer();
  return deferred.promise;
}

The requesting application can then call the then() method on the promise object to register successCallback, errorCallback, and notifyCallback functions using the following syntax:

promise.then(successCallback, [errorCallback], [notifyCallback])

The following shows a sample implementation of the then() function:

var promise = makeDeferredRequest();
promise.then(
  function successCallback(value){
    //handle success
  },
  function errorCallback(value){
    //handle error
  },
  function notifyCallback(value){
    //handle notify
  },

From the deferred service side you can use the methods described in Table 9.6 to handle notifying the requesting application of the status of the request.

Image

Table 9.6 Methods Available on a Deferred Object of the $q Service

The “Implementing a Database Access Service” section of Chapter 10, “Creating Your Own Custom AngularJS Services,” shows a good example of using the $q service to handle the deferred responses to remote database requests.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset