Web Service in AngularJS

Introduction to web service and JSON

Here, we are not describing what is a web service in detail, but we will see, how we can use Web service in AngularJS.

Web Service: A web service is software that is available over the internet. Web service is platform independent and internally uses XML.

JavaScript Object Notation (JSON)

JSON is similar to XML and uses a subset of JavaScript. JSON and XML are human readable formats and are language independent. JSON include arrays to describe the structured data.

AngularJS provides many inbuilt services such as, $http, $route, $window, $location etc. These service can be injected in controller function same as $scope. You can also create custom service.

There are two ways to create a custom service.
  • factory
  • service

Consuming ASP.NET web service in AngularJS and $http

Let us try to see with the help of an example, how to consume ASP.NET web service in AngularJS.

Step 1: In this example first we create a database table in SQL server.

Database name : Employee
Table name :Emp

database

Step 2: Now we will create an ASP.NET web service that will fetch the employee data from the database.

First create a class name Employee and write auto implemented properties in this class.
These properties will be initialized by data reader objects. We will serialize the Employee class object by using JavaScriptSerializer class. JavaScriptSerializer class is available in System.Web.Script.Serialization namespace.

Hierarchy of files and folders are given below.

file hierarchy

Code for Employee.cs file.

using System;
public class Employee
{
     public int EmpID { get; set; }
     public string EmpName { get; set; }
     public string Gender { get; set; }
     public string Salary { get; set; }
     public string EmpAddress { get; set; }
     public Employee()
     {
     }
}


Step 3: Now create a web service.

We have provided the webservice name as EmployeeDetailService. In this service we created a method GetEmployeeDetail() that is associated with [WebMethod] attribute. This method initialized all the properties of employee class.

In this service we want to fetch the data from employee data, so first write namespaces related to ADO.NET. We want this service to be called from javascript so uncomment the attribute
[System.Web.Script.Services.ScriptService]

After initialization of employee class, we will serialize it by using Serialize() method of JavaScriptSerializer class.

Serialize() method will convert our employee object in JSON format.

EmployeeDetailService.asmx file

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Script.Services;

///<summary>
/// Summary description for EmployeeDetailService
///</summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class EmployeeDetailService : System.Web.Services.WebService
{
     public EmployeeDetailService ()
     {
     }
     [WebMethod]
     [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
     public void GetEmployeeDetail()
     {
          List<Employee> empList = new List<Employee>();
          using (SqlConnection con = new SqlConnection ("Integrated Security=SSPI; Persist Security Info=False; Initial Catalog=Employee; Data Source=USER"))
          {
               SqlCommand cmd = new SqlCommand ("select * from emp", con);
               con.Open();
               SqlDataReade rdr = cmd.ExecuteReader();
               while(dr.Read())
               {
                    Employee empObj = new Employee();
                    empObj.EmpID = Convert.ToInt32(dr["EmpId"]);
                    empObj.EmpName=dr["Name"].ToString();
                    empObj.Gender = dr["Gender"].ToString();
                    empObj.Salary = dr["Salary"].ToString();
                    empObj.EmpAddress = dr["Address"].ToString();
                    empList.Add(empObj);
               }
          }      
          JavaScriptSerializer jsObj = new JavaScriptSerializer();
          jsObj.Serialize(empList);
     }    
}


In this web service, we have used table name as Emp, database as Employee and server as User in connection string. You can use names according to your needs and system settings.

Step 4: To retrieve the data from the database we will use $htttp service.

$http object will communicate with remote server. It sends a request to the server. The ASMX service then sends a response in JSON format, which will be parsed and consumed in AngularJS.
We will inject the $http service in controller function as parameter:

var myController = function ($scope, $http)

For calling our web service “EmployeeDetailService”, we need to use the $http.get() method of AngularJS. In the get method we have to pass the method name with service name as $http.get('EmployeeDetailService.asmx/GetEmployeeDetail')

Here the name of the service is 'EmployeeDetailService.asmx’ and the function name is GetEmployeeDetail'. This request processed asynchronously, it means that data may not available immediately.  When the request completes another function named as then() is called that takes another javascript function as parameter. This inner function will get the response from the server. $scope object will initialize with the response data.

$scope.employees = response.data;

Code for Script.js file.

/// <reference path="angular.min.js" />
/// <reference path="../EmployeeDetailService.asmx" />
var myApp = angular.module("myModule", []);
var myController = function ($scope, $http)
{   
     $http.post('EmployeeDetailService.asmx/GetEmployeeDetail')
     .then(function (response)
     {
          $scope.employees = response.data;
     });   
};
myApp.controller("myCont", myController);


In the above code we used $http.post() in place of $http.get() method.
If you write $http.get in place of $http.post, then you will not get the result as expected. If you want that $http.get method should work, then do the slide change in web.config file as given below.

Code for Web.config file.

<?xml version="1.0"?>
<configuration>
     <system.web>
          <compilationdebug="true" targetFramework="4.0"/>
          <webServices>
               <protocols>
               <addname="HttpGet"/>
               </protocols>
          </webServices>
     </system.web>
</configuration>


Code for Demo.html file.

<!DOCTYPE html>
<html ng-app="myModule">
     <head>
          <script src="Scripts/angular.min.js" type="text/javascript"></script>
          <script src="Scripts/Script.js"></script>
          <style>
               table, th, td
               {
                    border: 1px solid grey;
                    border-collapse: collapse;
                    padding: 5px;
               }
               table tr:nth-child(odd)
               {
                    background-color: #ffe6e6;
               }
               table tr:nth-child(even)
               {
                    background-color: #ccffcc;
               }
          </style>
     </head>
     <body style="font-family:Arial; font-size:medium; color:darkblue">
               <div ng-controller="myCont">
               <h3>Using web service in AngularJS.</h3>
               <br/>
               <table>
                    <tr>
                         <th>EmpID</th>
                         <th>Name</th>
                         <th>Gender</th>
                         <th>Salary</th>
                         <th>Address</th>
                    </tr>
                    <tr ng-repeat="e in employees">
                         <td>{{e.EmpID}}</td>
                         <td>{{e.EmpName}}</td>
                         <td>{{e.Gender}}</td>
                         <td>{{e.Salary}}</td>
                         <td>{{e.EmpAddress}}</td>
                    </tr>
               </table>
          </div>
     </body>
</html>


Step 5: Execute the Demo.html file you will get the output as follows

Output:
webservices

In the above example we have used $http.get() shortcut method. Instead of using $http.get() method we can also do the same task by using $http as a function.

var myController = function ($scope, $http)
{   
     $http({
               method : ‘GET’ ,
               url :'EmployeeDetailService.asmx/GetEmployeeDetail'
     })
     .then(function (response)
     {
          $scope.employees = response.data;
     });   
};
myApp.controller("myCont", myController);

$log service

$log service is another built in service that is used to log the response object to the console. This service is mainly used for debugging and troubleshooting. $log service has info() method which takes the response object as parameter. It will log the object on the console window. You can see the different properties of the object on consol. Run you application on google chrome and press F12, then you can able to see the properties of object.

If there is any error in your application, then you can also log this error on console or display it on browser by using binding expression.

Methods:
  • log()
  • Info()
  • warn();
  • error();
  • debug()
For using $log service, you can change the controller function in previous example as follows.

var myApp = angular.module("myModule", []);
var myController = function ($scope, $http, $log)
{
     var successFunction=function(response)
     {
          $scope.employees = response.data;
          $log.info(response);
     }
     var errorFunction= function (response)
     {
          $scope.error = response.data;
     }
     $http.get('EmployeeDetailService.asmx/GetEmployeeDetail')
     .then(successFunction, errorFunction);    
};
myApp.controller("myCont", myController);


In this code we have created two functions as successFunction and errorFunction. After successful response we passed these functions in then() function.

You can inject the $log service in the same manner as you injected $http service.
When you run the code you will find that object is logged in console.

Note: Run the code on google chrome and press F12. You will see the output something like as

log function

You can also show the error message on the browser by using the binding expression as
{{error}}
The second function will give the error response if something is going wrong.

var errorFunction= function (response)
{
     $scope.error = response.data;
}


For getting the error purposefully we have changed the name of method of web service that is passed in get() method as

$http.get('EmployeeDetailService.asmx/GetEmployee')

We changed the method name as GetEmployee in place of GetEmployeeDetail, and then you will see the error as given below.

Output:
webservice in angularjs

$location service in AngularJS.

$location service is used to parse the URL in the browser address bar. If you want to change the current URL in the browser then, you can use $location service. $location service and browser address bar is synchronized with each other means if you make any changes in the address bar, then it will reflect in the $location service and change in $location will be shown in the browser address bar. It does not reload full page if you change the URL.

Impotant Methods of $location service:
  • absUrl()
  • url()
  • protocol()
  • host()
  • port()
  • path()
  • hash()
You can inject the $location service in the same way as you injected the $http service in the controller function.

Code for Script.js file

/// <reference path="angular.js" />

var myApp = angular.module("myModule", []);
var myController = function ($scope, $location)
{
     $scope.myUrl = $location.absUrl();
     $scope.myProtocol = $location.protocol();
     $scope.myHost = $location.host();
     $scope.myPort = $location.port();   
};
myApp.controller("myCont", myController);


Code for Demo.html file

<!DOCTYPE html>
<html ng-app="myModule">
     <head>
          <script src="Scripts/angular.js"></script>
          <script src="Scripts/Script.js"></script>
          <style>
               table, th, td
               {
                    border: 1px solid grey;
                    border-collapse: collapse;
                    padding: 5px;
               }
               table tr:nth-child(odd)
               {
                    background-color: #ffe6e6;
               }
               table tr:nth-child(even)
               {
                    background-color: #ccffcc;
               }
          </style>
     </head>
     <body style="font-family:Arial; font-size:medium; color:darkblue">
          <div ng-controller="myCont">
               <h3>Using $location service in AngularJS.</h3>
               <br/>
               <table>
                    <tr><th>URL</th><td>{{myUrl}}</td></tr>
                    <tr><th>Protocol</th><td>{{myProtocol}}</td></tr>
                    <tr><th>Host</th><td>{{myHost}}</td></tr>
                    <tr><th>Port</th><td>{{myPort}}</td></tr>
               </table>
          </div>
     </body>
</html>


Execute the Demo.html file you will get the output. The output may vary as it depends on your system settings.

Output:
location service