ASP.NET MVC 5 Promise and handling multiple async calls in angular

This article describes about how to make multiple async service calls in angularjs and show the progress during the service calls execution.

Here, we are going to explore on
  1) Create WebAPI with multiple async services
   2) Invoke the services from angular
   3) Show the progress bar

Create WebAPI with multiple async services
Create a new MVC project by selecting WebApi template as below.


Open theController(inherited from ApiController) class file and define the RoutePrefix as below.

   [RoutePrefix("api/test")]
    public class ValuesController : ApiController
    {}

Create two async controller (Api) actions one with Post and another one with Get with defined Routes as below.

       [Route("GetUsersFilterByName")]
        [HttpPost]
         public async Task<IHttpActionResult> GetUsersFilterByName(string query)
        {
          
            var list = await Service1.GetUsers(query);

             return this.Ok(list);
        }

        [Route("GetData")]
        [HttpGet]
         public async Task<IHttpActionResult> GetData()
         {

             return this.Ok(string.Empty);
        }

As defined custom Routes, the service url format looks like http://<<servername>>/api/test/GetUsersFilterByName with parameters if any.

Invoke the services from Angular
Create a new MVC project and add the angular core nugget packages. Please refer my previous article for setting up the angular environment in MVC (SPA) project.

http://nullskull.com/a/10479043/spa-single-page-application-in-mvc-5-and-angularjs.aspx

Add the $http and $q directives for your angular controller where you are going to invoke the api service calls.

app.controller('homeController', ["$scope", "$http",  "$q, function ($scope, $http, $q) { }]);

$http is used to invoke the services and it has Get, Post, Put and Delete functions which will be used based on the service call type.
$q is a service that helps you to run functions asynchronously and returns the response when done with processing. This is as similar to deferred and promises in jQuery.

Refer the angular site for documentation.
https://docs.angularjs.org/api/ng/service/$q

Let’s create a function to invoke the service from angular.

var getUsers = function () {
        webUrl = 'http://localhost:50858/api/test/GetUsersFilterByName?query=A';
        var q = $q.defer();

        $http.post(webUrl).then(function (response) {
            q.resolve(response.data);
        },
         function (error) {
             q.reject(null);
         });

         return q.promise;
    };

Here, promise contains the service status whether success of failure.

Now, call the multiple service functions as below.

// first call
    getUsers().then(function (userResponse) {
        $scope.users = userResponse;

        // second call
        getData().then(function (dResponse) {

            $scope.dataResponse = dResponse;

            
        });

    });

From above, first executes first async service function and followed by subsequent function calls. If any service function fails, promise stops the execution of subsequent calls.

Show the progress bar
In most of the projects, we have to show the progress bar if something is happing in background. Let’s implement the progress bar from angular.

Add the ngProgress script and css files to your Scripts and Content folder and reference them in bundle.config as below.


Let’s add the ngProgress directive to angular module and use ngProgressFactory to angular controller.

var app = angular.module('angularspa', ["ngRoute", "ngProgress"]);
app.controller('homeController', ["$scope", "$http", "$rootScope", "$q", "ngProgressFactory", function ($scope, $http, $rootScope, $q, ngProgressFactory) { }]);

Create a instance for progress bar and start the progress as below.

// start Progress bar
    $scope.progressbar = ngProgressFactory.createInstance();
    $scope.progressbar.start();

Now, let’s use this progress bar in multiple async service calls function as below.

// first call
    getUsers().then(function (userResponse) {
        $scope.users = userResponse;

        // second call
        getData().then(function (dResponse) {

            $scope.dataResponse = dResponse;

             // complete the Progress
            $scope.progressbar.complete();

        });

    });

From above, just completing the progress once the service functions are executed.

You can reset the progress by setting $scope.progressbar.reset();

Download the working sample from below location. Make sure to add the missing nugget packages as they were removed because of size constraint.
http://nullskull.com/FileUpload/-407123783_Angular-async.zip      

By Siva Jagan Dhulipalla   Popularity  (4592 Views)