Last Updated: February 25, 2016
·
18.03K
· yassershaikh

$q and Promise with ajax call in AngularJS

In this quick tip I have a function in my controller which will make use of a service which get some data using an ajax request. The function returns the status of the get data request using a deferred object.

Before you read further take a quick trip to this link and get acquainted with the basics of $q (promise/deferred implementation)

Service

Consider a simple service with a getAbc() function.

angular
    .module('myApp')
    .service('myDataService', ['$http', function ($http) {
        this.getAbc = function ($params) {
            return $http({
                headers: { 'Content-Type': 'application/json' },
                url: '/api/ABC',
                method: "POST",
                data: $params
            });
        };
    } ]);

Controller

In your controller make sure to inject the $q dependency like shown below.

.controller('GridController', ['$scope', '$http', 'myDataService', '$q', function ($scope, $http, myDataService, $q) {...

$q.defer()

Below is the code where I now use the service myDataService we just created.

$q.defer() constructs a new instance of deferred, The purpose of the deferred object is to expose the associated Promise instance as well as APIs that can be used for signaling the successful or unsuccessful completion, as well as the status of the task.

$scope.DoSomething = function() {

    var paramsToPost = null; // you could pass something useful here.

    var deferred = $q.defer();
    deferred.notify();

    myDataService.getAbc(paramsToPost)
        .success(function() {
            deferred.resolve();
        })
        .error(function() {
            deferred.reject();
        });

    return deferred.promise;
};

Methods

  • resolve(value) – resolves the derived promise with the value. If the value is a rejection constructed via $q.reject, the promise will be rejected instead.

  • reject(reason) – rejects the derived promise with the reason. This is equivalent to resolving it with a rejection constructed via $q.reject.

  • notify(value) - provides updates on the status of the promise's execution. This may be called multiple times before the promise is either resolved or rejected.

var promise = DoSomething();
promise.then(function(successParam) { // success callback
  console.log("success");
}, function(rejectParam) { // error callback with reason
  console.log("rejected");
}, function(notifyParam) { // notification
  console.log("notify");
});

Hope this helps :)

References
- https://docs.angularjs.org/api/ng/service/$q

Links you might need if you are working with $q

Also check out interview questions and interview experiences and share your feedback on this article in the comments below. Cheers !

3 Responses
Add your response

Thanks for this. I have found $q to be really useful in AngularJS and promises are a very useful design pattern when dealing with asynchronous services.

over 1 year ago ·

Hey rmcdaniel! Thanks for writing in. I too have found this to be very useful :)

over 1 year ago ·

Great post!

over 1 year ago ·