How To Consume WebAPI Using AngularJS

Consume web api in AngularJS

In development, sometimes we consume data from different sources, for example,  webservices. Today in this article we are going to learn,

  • How to consume webapi using angularjs.
  • ng-repete directive in angularjs

What is WEBAPI

As we all know, API stands for Application programming interface. The main purpose of webapi is to create restful services. Web API is consumed by a broad range of clients like

  1. IOT (Internet of Things)
  2. Mobile Apps
  3. Web based Apps
  4. Desktop Apps

So we are going to learn consuming services through angularjs. So let's take a look.

Step 1
- Open Visual Studio

Step 2
- File>>New>> Project

Project

Choose Asp.Net WebApplication

Step 3- Select WebAPI

Project

Click on OK Button.

Check the Solution Explorer.

Project

Here you can see, it looks like an MVC Application, where we have Models, View and Controller. But my friend, here we will create webapis.

Now the question arises:  What is the diffrence between WebAPI Controller and MVC Controller?

Project

  • If , talking about MVC Controller, mvc controller will be inherited by Controller and WebAPI Controller will be inherited by ApiController. This is the biggest diffrence between these two.
  • And webAPI is designed for returning data in the form of JSON and XML.

So in this example we have one StudentDB database, where we have studentsinformations. So first create StudentDB and one table StudentMaster.

Project

Below is the data into StudentMaster table.

Project

  • Now create an edmx file, and connect StudentDB with your Entity. In this example my entity name is StudentEntity.

Project

Click on Add Button, now the basis of wizard, create an edmx file.

  • Once you click on the finish button your screen looks like

Project

Now open HomeController, by default HomeController will be inherited by Controller like this HomeController:Controller, change this to HomeController:ApiController, and copy below code.

  1. usingAngularwithWebAPI.DbContext;  
  2. using System;  
  3. usingSystem.Collections.Generic;  
  4. usingSystem.Linq;  
  5. usingSystem.Web;  
  6. usingSystem.Web.Http; // This namespace is responsible for IHttpActionResult  
  7. usingSystem.Web.Mvc;  
  8.   
  9. namespaceAngularwithWebAPI.Controllers {  
  10.     publicclassHomeController: ApiController {  
  11.         DbContext.StudentEntitiesstudentEntities = newDbContext.StudentEntities();  
  12.         publicIHttpActionResultGetStudents() {  
  13.             var query = studentEntities.StudentMasters.ToList();  
  14.             return Ok(query);  
  15.         }  
  16.     }  
  17. }   
  • Now let's understand the above code line by line. You can see in the above code we have HomeController:ApiController, because we want to work on WebAPI
  • I create Object of StudentEntities, so we can get all the table SPs from StudentDB very easily.
  • After that we have Public IHttpActionResult, IHttpAtionResult is introduced in WebAPI 2, this needs a namesapceSystem.web.http. IHttpActionResult use for building HttpResponseMessages.
  • Now run your service.

    usingAngularwithWebAPI.DbContext; using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Web; usingSystem.Web.Http; // This namespace is responsible for IHttpActionResult usingSystem.Web.Mvc;  namespaceAngularwithWebAPI.Controllers {     publicclassHomeController: ApiController {         DbContext.StudentEntitiesstudentEntities = newDbContext.StudentEntities();         publicIHttpActionResultGetStudents() {             var query = studentEntities.StudentMasters.ToList();             return Ok(query);         }     } }

  • After that we are getting a list of student data into query, and then returning OK(query), that means this will convert this into Array XML of StudentMaster, with the use of it we can easily console this into our angularcode.

Let's come to our Angular code.

Script.js

  1. vartestApp = angular  
  2.     .module("testModule", [])  
  3.     .controller("testController", function($scope, $http) {  
  4.         $http.get('http://localhost:50623/api/home/getstudents').then(function(response) {  
  5.             $scope.students = response.data;  
  6.         });  
  7.     });  
Here I use $http, $http is used for sending get, put, post and delete kinds of requests into the server, in the then part, after getting the result, we can store it into $scope variable.

$http.get('url')- here we have to call our url, so please first, call your webapi and check your port number, and then use your url into $http.get.
Now, call $scope variable into your pge.

index.html
  1. <!DOCTYPEhtml>  
  2. <htmlng-apphtmlng-app="testModule">  
  3.   
  4.     <head>  
  5.         <scriptsrcscriptsrc="Scripts/angular.min.js">  
  6.             </script>  
  7.             <scriptsrcscriptsrc="Scripts/js/Script.js">  
  8.                 </script>  
  9.                 <title></title>  
  10.                 <metacharsetmetacharset="utf-8" />  
  11.     </head>  
  12.   
  13.     <body>  
  14.         <divng-controllerdivng-controller="testController">  
  15.             <tablebordertableborder="1">  
  16.                 <thead>  
  17.                     <tr>  
  18.                         <th>  
  19.                             Student Id  
  20.                         </th>  
  21.                         <th>  
  22.                             Name  
  23.                         </th>  
  24.                         <th>  
  25.                             Address  
  26.                         </th>  
  27.                         <th>  
  28.                             Email  
  29.                         </th>  
  30.                         <th>  
  31.                             Phone  
  32.                         </th>  
  33.                     </tr>  
  34.                 </thead>  
  35.                 <trng-repeattrng-repeat="sinstudents">  
  36.                     <td>  
  37.                         {{s.Id}}  
  38.                     </td>  
  39.                     <td>  
  40.                         {{s.Name}}  
  41.                     </td>  
  42.                     <td>  
  43.                         {{s.Address}}  
  44.                     </td>  
  45.                     <td>  
  46.                         {{s.Email}}  
  47.                     </td>  
  48.                     <td>  
  49.                         {{s.Phone}}  
  50.                     </td>  
  51.                     </tr>  
  52.                     </table>  
  53.                     </div>  
  54.     </body>  
  55.   
  56.     </html>  
In the above code, i use ng-repete directive, with the use of this directive, we can call list information, so we have scope variable students, so i use ng-repete='s in student so this will give me all the related object data one by one. You can see, I used ng-repete<tr> section because we want data row wise, so every time ng-repete loop runs, this wil create new <tr> row with data.

Now it's time to check the output.

<!DOCTYPEhtml /> <htmlng-app="testmodule">      <head>                                       <title></title>                 <metacharset="utf-8" />     </head>      <body>         <divng-controller="testcontroller">             <tableborder="1">                 <thead>                     <tr>                         <th>                             Student Id                         </th>                         <th>                             Name                         </th>                         <th>                             Address                         </th>                         <th>                             Email                         </th>                         <th>                             Phone                         </th>                     </tr>                 </thead>                 <trng-repeat="sinstudents">                     <td>                         {{s.Id}}                     </td>                     <td>                         {{s.Name}}                     </td>                     <td>                         {{s.Address}}                     </td>                     <td>                         {{s.Email}}                     </td>                     <td>                         {{s.Phone}}                     </td>                     </tr>                     </table>                     </div>     </body>      </html>

You can see, finally our data is consumed by webapi. We can see all student data row by row through ng-repete.

If you have any query regarding this article or suggesions, please send your  valuable comments.