AngularJS $http service in an ASP.NET MVC app
Posted by: Mahesh Sabnis ,
on 10/19/2015,
in
Category AngularJS
Abstract: In this article, we will how to use Angular’s $http service in an ASP.NET MVC app to retrieve data from the server.
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.post
- $http.put
- $http.delete
- $http.patch
New to AngularJS ? Read this first: https://www.dotnetcurry.com/angularjs/1062/website-using-angularjs-aspnet-webapi
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 Module
var 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 Controller
app.controller('ctrl', function ($scope,ms) {
loadData();
function loadData() {
//The controller call the function from the service
var promiseGetData = ms.getData();
//Callback with success and failure
promiseGetData.then(function (res) {
$scope.Persons = res.data;
$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 getData function which makes call to the Web API and returns the promise object of name resp. The Angular controller of name cltl is passed with the Angular Service object dependency.
The controller defines loadData() function. This function makes a call to the getData function of the service and retrieves the promise object. The code then calls the then function 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:
$http.post
this.postData = function (person) {
var resp = $http({
method: "post",
url: "http://localhost:15377/api/TestAPI",
data:person
});
return resp;
};
$http.put
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.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @
maheshdotnet or connect with him on
LinkedIn