Introduction To AngularJS – Day Eighteen

In the 18th day of AngularJS article series, we are going to be learning the next key players/concept of AngularJS, and understanding the concept of Built in Services of AngularJS. Before moving on to key players/concepts of AngularJS, please read my previous articles:

  1. Introduction to AngularJS – Day 1
  2. Introduction to AngularJS – Day 2
  3. Introduction to AngularJS – Day 3
  4. Introduction to AngularJS – Day 4
  5. Introduction to AngularJS – Day 5
  6. Introduction to AngularJS – Day 6
  7. Introduction to AngularJS – Day 7
  8. Introduction to AngularJS – Day 8
  9. Introduction to AngularJS – Day 9
  10. Introduction to AngularJS – Day 10
  11. Introduction to AngularJS – Day 11
  12. Introduction to AngularJS – Day 12
  13. Introduction to AngularJS – Day 13
  14. Introduction To AngularJS – Day 14
  15. Introduction To AngularJS – Day 15
  16. Introduction To AngularJS – Day 16
  17. Introduction to AngularJS – Day 17

AngularJS provides many built in services. For example:
services
$http Service

The $http service is used to make Ajax call to get the server data.

  1. $http service provides Ajax functionality.
  2. Uses the browser's XmlHttpRequest object.
  3. Makes asynchronous requests.
  4. Supports multiple HTTP verbs:

    • $http.get
    • $http.post
    • $http.put
    • $http.delete
    • $http.jsonp
    • $http.head

Using this $http service you can access data from any .json file, you can call PHP, Web Api etc.

Syntax:

  1. /// <reference path="angular.min.js" />  
  2. var app = angular.module("myApp", []);  
  3.   
  4. //Creating controller & injecteing $http service in controller  
  5. app.controller("myController", function ($scope, $http) {  
  6.       
  7. In the above we inject the ‘$http’ service and how to use it see following code:  
  8. $scope.init = function () {  
  9.         $http({  
  10.             method: "GET",              
  11.             url: "http://localhost:62039/api/Employees",  
  12.             headers: { 'Content-Type''application/x-www-form-urlencoded' }  
  13.         }).  
  14.         success(function (data, status, headers, config) {  
  15.             $scope.employees = data;  
  16.         }).  
  17.         error(function (data, status, headers, config) {  
  18.               
  19.         });  
  20.     };  
Accessing $http Response Data:

$http makes asynchronous calls:
 
  1. Relies on $q service's deferred/promise APIs
  2. Access data by calling then() or success()/error()

    code

The above screen shot you can see colored, to access data using success/then.

Example:

In the below demo example we are going to see how we can you ‘$http’ service for CRUD operations. Here we use Web Api to access or save data to database.

app.js

  1. /// <reference path="angular.min.js" />  
  2. var app = angular.module("myApp", []);  
  3.   
  4. //Creating controller & injecteing $http service in controller  
  5. app.controller("myController", function ($scope, $http) {  
  6.       
  7.     $scope.update = false;  
  8.   
  9.     //Initialize data  
  10.     $scope.init = function () {  
  11.         $http({  
  12.             method: "GET",              
  13.             url: "http://localhost:62039/api/Employees",  
  14.             headers: { 'Content-Type''application/x-www-form-urlencoded' }  
  15.         }).  
  16.         success(function (data, status, headers, config) {  
  17.             $scope.employees = data;  
  18.         }).  
  19.         error(function (data, status, headers, config) {  
  20.               
  21.         });  
  22.     };  
  23.   
  24.     //Add Employee  
  25.     $scope.addEmployee = function () {  
  26.         $scope.para = {  
  27.             Id: $scope.temp.id,  
  28.             Name: $scope.temp.name,  
  29.             Designation: $scope.temp.desg,  
  30.             City: $scope.temp.city  
  31.         };  
  32.   
  33.         $http.post('http://localhost:62039/api/Employees/PostEmployee', $scope.para).  
  34.         success(function (data, status, headers, config) {  
  35.             if (data) {  
  36.                 $scope.temp = {  
  37.                     id: '',  
  38.                     name: '',  
  39.                     desg: '',  
  40.                     city: ''  
  41.                 };  
  42.                 if (!$scope.update) {  
  43.                     $scope.employees.push(data);  
  44.                 }                 
  45.             }  
  46.         }).  
  47.         error(function (data, status, headers, config) {  
  48.   
  49.         });      
  50.           
  51.     };  
  52.   
  53.     //Update Employee  
  54.     $scope.editEmployee = function (emp) {  
  55.         $scope.temp = {  
  56.             id: emp.Id,  
  57.             name: emp.Name,  
  58.             desg: emp.Designation,  
  59.             city: emp.City  
  60.         };  
  61.         $scope.index = $scope.employees.indexOf(emp);  
  62.     };  
  63.   
  64.     //Delete Employee  
  65.     $scope.delEmployee = function (emp) {  
  66.         var r = confirm("Are you sure want to delete this employee!");  
  67.         if (r == true) {  
  68.             $http({  
  69.                 method: "DELETE",  
  70.                 url: "http://localhost:62039/api/Employees/" + emp.Id,  
  71.                 headers: { 'Content-Type''application/x-www-form-urlencoded' }  
  72.             }).  
  73.             success(function (data, status, headers, config) {  
  74.                 if (data.success) {  
  75.                     var index = $scope.employees.indexOf(emp);  
  76.                     $scope.employees.splice(index, 1);  
  77.                 }  
  78.             }).  
  79.             error(function (data, status, headers, config) {  
  80.   
  81.             });  
  82.         }  
  83.     };  
  84.   
  85.     //Update Employee  
  86.     $scope.updateEmployee = function () {  
  87.         $scope.update = true;  
  88.         $scope.addEmployee();          
  89.     };  
  90.       
  91. });  
index.html
  1. <!DOCTYPE html>  
  2. <html ng-app="myApp">  
  3. <head>  
  4.     <title>Welcome to C# Corner</title>  
  5.     <meta charset="utf-8" />  
  6.     <link href="css/bootstrap.min.css" rel="stylesheet">  
  7.     <link href="css/font-awesome.min.css" rel="stylesheet">  
  8.     <link href="css/animate.min.css" rel="stylesheet">  
  9.     <link href="css/style.css" rel="stylesheet">  
  10.     <script src="scripts/jquery.min.js"></script>  
  11.     <script src="scripts/bootstrap.min.js"></script>  
  12.     <script src="scripts/angular.min.js"></script>  
  13.     <script src="app/app.js"></script>  
  14.      
  15. </head>  
  16. <body ng-controller="myController" ng-init="init()">  
  17.       
  18.     <div class="container">  
  19.         <!--<h1 class="text-center">Welcome to C# Corner</h1>-->  
  20.         <h3 class="text-center">AngularJS CRUD Operations using $http Services</h3>  
  21.   
  22.         <div class="row mt80">  
  23.             <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 animated fadeInDown">                  
  24.                   
  25.                     <div class="form-group">  
  26.                         <label>Name</label>  
  27.                         <input type="text" class="form-control" placeholder="Name" data-ng-model='temp.name'>                          
  28.                     </div>  
  29.                     <div class="form-group">  
  30.                         <label>Designation</label>  
  31.                         <input type="text" class="form-control" placeholder="Designation" data-ng-model='temp.desg'>                          
  32.                     </div>  
  33.                     <div class="form-group">  
  34.                         <label>City</label>  
  35.                         <input type="text" class="form-control"placeholder="City" data-ng-model='temp.city'>                          
  36.                     </div>                                          
  37.                     <div class="text-center">  
  38.                         <input ng-hide="temp.id" type="button" class="btn btn-save" ng-click="addEmployee()" value="Add"/>  
  39.                         <input ng-hide="!temp.id" type="button" class="btn btn-save" ng-click="updateEmployee()" value="Update"/>  
  40.                     </div>  
  41.                   
  42.             </div>  
  43.   
  44.             <div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 animated fadeInUp">  
  45.                 <div class="table-responsive">  
  46.                     <table class="table table-bordered table-hover table-striped">  
  47.                         <thead>  
  48.                             <tr>  
  49.                                 <th width="5%">ID</th>  
  50.                                 <th width="20%">Name</th>  
  51.                                 <th width="20%">Designation</th>  
  52.                                 <th width="20%">City</th>  
  53.                                 <th width="20%">Action</th>  
  54.                             </tr>  
  55.                         </thead>  
  56.                         <tbody>  
  57.                             <tr data-ng-repeat="emp in employees | orderBy : '-id'">  
  58.                                 <th scope="row">{{emp.Id}}</th>  
  59.                                 <td> {{emp.Name}} </td>  
  60.                                 <td> {{emp.Designation}} </td>  
  61.                                 <td> {{emp.City}} </td>  
  62.                                 <td> <span data-ng-click="editEmployee(emp)"> Edit</span> | <span data-ng-click="delEmployee(emp)">Delete</span> </td>  
  63.                             </tr>  
  64.                         </tbody>  
  65.                     </table>  
  66.                 </div>  
  67.             </div>  
  68.         </div>  
  69.     </div>  
  70. </body>  
  71. </html>  
Output:

Before running the html file run your Web Api application and then open the html file. After opening html file you can see output as follows in browser:

Output

Next, I am going to add employee record in that see below screen shot:

Output

Click on ‘Add’ button, record is added. See side table the added record:

Output

Now, next click on side table last column on ‘Edit’:

Edit

After click on ‘Edit’, it will populate data in left side for see. I am going to change the ‘Designation’:

Designation

Next, click on ‘Update’ button.

Update

See above screen shot the ‘Designation’ field is updated. Now, click on ‘Delete’ action of ‘ID’ is 9, it will prompt message ‘Are you sure want to delete the employee!’ as follows:

message

Here, I click on ‘OK’ button and record ‘ID-9’ is deleted see below screen shot:

OK

Great, $http service in AngularJS with example created successfully!

Summary

I hope that beginners as well as students can understand the concept of $http service in AngularJS with exampls. If you have any suggestions regarding this article, then please contact me. Stay tuned for other concepts of AngularJS coming soon!

Thanks for reading. Learn it! Share it!

Read more articles on AngularJS:

Up Next
    Ebook Download
    View all
    Learn
    View all