Wednesday, December 24, 2014

Return promise from service of AngularJS

Hope we all have basic concept of promise in Asynchronous operation. The implementation of AJAX with asynchronous operation heavily depends on promise.

The semantics of Angular dictate that you use promise as a sort of ‘Callback handle’ – do something asynchronous in a service, return a promise and when the asynchronous operation done, then function of promise will trigger.

By keeping this theory in mind, let’s implement same in AngularJS.

Here is sample code for Service, we have used factory to implement service. We have used $q service of Angular to implement promise and defer. 

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

        app.factory('myDataFactory', function ($http,$q) {

            return {
                getdata: function () {
                    var deferred = $q.defer();

                    $http.get('../DummyData/getData').success(function (value) {
                            deferred.resolve(value);
                    }).error(function (msg, code) {
                            deferred.reject(msg);
                    });
                    return deferred.promise;
                }
            };

        });


Here is code in service, Which is returning a simple object.

public class person
    {
        public string name { get; set; }
        public string surname { get; set; }
    }
    public class DummyDataController : Controller
    {
      
        public ActionResult Index()
        {
            return View("Index");
        }

        public string getData()
        {
            return JsonConvert.SerializeObject(
             new person { name = "Sourav", surname = "Kayal" });
        }

    }

Now, we will consume the service from controller. Here is sample code to consume the service.

app.controller('myController', function ($scope,  myDataFactory) {

            var returnValue = myDataFactory.getdata();
            returnValue.then(function (retData) {
                alert(JSON.stringify(retData));
            }, function (error) {
                alert(JSON.stringify(error));
            });

        });

then() function will get execute if promise is success type and if it failure then error function will get execute.


No comments:

Post a Comment