AngularJS $http service in an ASP.NET MVC app


AngularJS provides built-in support to communicate with a server. You can either use an XMLHttpRequest object (async request) or JSON (sync or async request).

$http is a core Angular service that provides access to low-level interactions with remote Http services using the XMLHttpRequest object. The $http API is used to perform asynchronous operations and returns a promise object to the caller which can be used to receive notifications about the Ajax request. We can make use of then()method of the promise object to register callbacks. Other methods defined by a promise object are success (callback) and fail(callback) to handle success and fail respectively for the callback. The success callback function receives the data retrieved from the server, and the error callback receives details of any errors.

Note:.then() returns a new promise object that unwraps the AngularJS response. .success() returns the original $http promise.

Following is the list of method offered by $http

$http.get $ $http.put $http.delete $http.patch

New to AngularJS ?Read this first:

The Implementation

Lets’ implement Angular $http in an MVC application. Create a new ASP.NET MVC application using Visual Studio 2013. In this MVC application add a new Web API in the controllers folder of name TestAPIController with the following code:

public class TestAPIController : ApiController{string[] Names;List<PersonClass> Persons = new List<PersonClass>(); public TestAPIController(){Pesons.Add(new PersonClass() { FirstName = "Mahesh", LastName = "Sabnis" });Pesons.Add(new PersonClass() { FirstName = "Leena", LastName = "Sabnis" });Pesons.Add(new PersonClass() { FirstName = "Tejas", LastName = "Sabnis" });}public IEnumerable<PersonClass> Get(){return Persons;}}public class PersonClass{public string FirstName { get; set; }public string LastName { get; set; }}

In the same project, add Angular framework using NuGet package manager. (Right Click on the Project > Select Manage Nuget Packages > from the NuGet Package Manager Window select Angular, from the Angular List select Angular Core.). The Angular scripts will be added to the Scripts folder.

In the Scripts folder add a new JavaScript file of name Logic.js. Add the following code in it:

//The Modulevar app = angular.module('md',[]);//The service with the get method. app.service('ms', function ($http) {this.getData = function () {var resp = $http.get("http://localhost:15377/api/TestAPI");return resp;}; });//The Controllerapp.controller('ctrl', function ($scope,ms) {loadData();function loadData() {//The controller call the function from the servicevar promiseGetData = ms.getData();//Callback with success and failurepromiseGetData.then(function (res) {$scope.Persons =;$scope.Message = "Call Completed Successfully...";}, function (err) {$scope.Message = "Call failed" + err.status + " " + err.statusText;});}$scope.Person = {FirstName: "" ,LastName: ""}; });

The above code defines Angular Module of name md, and then defines an Angular service of the name ms.This service is injected with $http.This service defines getDatafunction which makes call to the Web API and returns the promiseobject of name resp.The Angular controller of name cltlis passed with the Angular Service object dependency.

The controllerdefines loadData()function. This function makes a call to the getDatafunction of the service and retrieves the promiseobject. The code then calls the thenfunction on the promise object and passes the success and error callback functions to it.

Editorial Note:For those who also use jQuery and find a striking similarity between jQuery $.ajax() and Angular’s $http, please note that jQuery uses deferred whereas Angular uses $digest of the $q service.

In the code, we have seen a $http.get method call. We can use other $http functions like post and put as shown in the following code:


this.postData = function (person) {var resp = $http({method: "post",url: "http://localhost:15377/api/TestAPI",data:person});return resp;};


this.postData = function (id,person) {var resp = $http({method: "post",url: http://localhost:15377/api/TestAPI/ +id,data:person});return resp;}; Conclusion:

In this article, we saw how to use Angular’s $http service to retrieve data from the server.