Handle asynchronous calls using promises and $q
15:46Introduction
It is very difficult in our angular application, when we using service and get a asynchronous call from it. Sometimes response is coming without any result. Because our request do not wait for coming value from server side. To resolve this problem angular give us $q constructor. So that we can get all the result. In this article I going to explain how to call asynchronously using promises and $q service.What is $q
$q service help us to run functions asynchronously, and return values after done the processing.$q have the three methods i.e.
i) then(successCallback, [errorCallback], [notifyCallback]): It calls one of the success or error callbacks asynchronously as soon as the result is available. The errorCallback and notifyCallback arguments are optional.
ii) catch(errorCallback): If we get return some error we handle it by this method.
iii) finally(callback, notifyCallback): This is useful to release resources or do some clean-up.
Create simple application
Go to visual studio > New > Project > Select any mvc application > OkAfter this create a new controller TestController.cs and create a view Index.cshtml.
We create a class name Employee and add a list value.
TestController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AngularJsPromise.Controllers { public class TestController : Controller { public ActionResult Index() { return View(); } public JsonResult getData() { List<Employee> emp = new List<Employee>(); try { emp.Add(new Employee() { FirstName = "Surajit", LastName = "Ghosh", Location = "Kolkata", Age = 29, MobileNo = "9856325641" }); emp.Add(new Employee() { FirstName = "Avijit", LastName = "Pramanik", Location = "California", Age = 35, MobileNo = "7852325641" }); emp.Add(new Employee() { FirstName = "Sourav", LastName = "Mondal", Location = "Kolkata", Age = 28, MobileNo = "8589632564" }); emp.Add(new Employee() { FirstName = "Amit", LastName = "Bhunia", Location = "Kolkata", Age = 29, MobileNo = "8596325690" }); emp.Add(new Employee() { FirstName = "Shantanu", LastName = "Nag", Location = "Kolkata", Age = 29, MobileNo = "7852149638" }); return Json(emp, JsonRequestBehavior.AllowGet); } catch (Exception) { return Json(emp, JsonRequestBehavior.AllowGet); } } } public class Employee { public string FirstName { get; set; } public string LastName { get; set; } public string Location { get; set; } public int Age { get; set; } public string MobileNo { get; set; } } }After that we create a servics file. In the service file we need to use $http and $q.
Promise return after comming the value from server side. If success return the resolve and if there will be getting any error it reject the promise.
service.js
var app = angular.module('myApp'); app.factory('myService', ['$http', '$q', function ($http, $q) { var fact = {}; fact.getData = function () { var deferred = $q.defer(); $http.get('/Test/getData', { cache: true }) .then(function (response) { if (typeof response.data === 'object') { deferred.resolve(response.data); } else { deferred.reject(response.data); } }, function (response) { deferred.reject(response.data); }); return deferred.promise; } return fact; }]);Now we need to create a controller file. In the controller we use getData service for fetching the value. The service value is store a array and send it to the view.
In the controller we create an object var myCtrl = this and use it to the view page.
controller.js
var app = angular.module('myApp', []); app.controller('myController', ['$scope', 'myService', function ($scope, myService) { var myCtrl = this; myCtrl.EmployeeList = []; myService.getData().then(function (data) { myCtrl.EmployeeList = data; }); }]);Now in the view page we need to add three files i.e. angular.js, controller.js and service.js. In this view we create a table and bing the service value using the ng-repeat. The view page is below:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="/js/angular.js"></script> <script src="/js/controller.js"></script> <script src="/js/service.js"></script> <style> table { border: 1px solid blue; padding: 1px; width: 500px; height: 183px; } table tbody tr th { font-size: 18px; background-color: brown; color: #fff; padding: 2px; text-align: center; } table tbody tr td { font-size:14px; color:#000; padding:2px; text-align:center; border-bottom: 1px solid #eeeeef; } </style> </head> <body ng-app="myApp" > <div style="margin-left:40%;margin-top:10%;" ng-controller="myController as myCtrl"> <table> <tr> <th>FirstName</th> <th>LastName</th> <th>Location</th> <th>Age</th> <th>Mobile Number</th> </tr> <tr ng-repeat="val in myCtrl.EmployeeList"> <td>{{val.FirstName}}</td> <td>{{val.LastName}}</td> <td>{{val.Location}}</td> <td>{{val.Age}}</td> <td>{{val.MobileNo}}</td> </tr> </table> </div> </body> </html>After run the application the browser view is below:
0 comments