Click here to Skip to main content
15,030,781 members
Articles / Programming Languages / C#
Tip/Trick
Posted 4 Oct 2016

Tagged as

Stats

26.2K views
6 bookmarked

Consume WEBAPI in Angularjs

Rate me:
Please Sign up or sign in to vote.
4.26/5 (8 votes)
4 Oct 2016CPOL3 min read
Today in this article, we are going to learn how to consume webapi using angularjs.

Introduction

In development, sometimes we are consuming data from different sources, example webservices. Today in this tip, we are going to learn:

  • How to consume webapi using angularjs
  • ng-repeat 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

Using the Code

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

Choose ASP.NET WebApplication.

Step 3

Select WebAPI.

Click on OK Button.
Check the Solution Explorer.

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 difference between WebAPI Controller and MVC Controller?

  • If, talking about MVC Controller, MVC controller will be inherited by Controller and WebAPI Controller will be inherited by ApiController. This is the biggest difference between those 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 students information. So, first create StudentDB and one table StudentMaster.

    Below is the data into StudentMaster table.

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

    Click on Add Button, now on the basis of wizard, create an edmx file.
    Once you click on the finish button, your screen looks like:

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

    C#
    using AngularwithWebAPI.DbContext;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Http;// This namespace is responsible for IHttpActionResult
    using System.Web.Mvc;
    
    namespace AngularwithWebAPI.Controllers
    {
        public class HomeController : ApiController
        {
            DbContext.StudentEntities studentEntities = new DbContext.StudentEntities();
            public IHttpActionResult GetStudents()
            {
                var query = studentEntities.StudentMasters.ToList();
                return Ok(query);
            }
        }
    }
  • Now let's understand the above code line by line. You can see in the above code that 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 namespace System.web.http. IHttpActionResult use for building HttpResponseMessages.
  • Now run your service.

After that, we are getting a list of student data into query, and then return OK(query). That means this will convert this into Array XML of StudentMaster, with the use of it we can easily, consume this into our angularcode.
Let's come to our Angular code.

Script.js

JavaScript
var testApp = angular
.module("testModule", [])
.controller("testController", function ($scope, $http) {
    $http.get('http://localhost:50623/api/home/getstudents').then(function (response) {
        $scope.students = response.data;
    });
});

Here, I use $http, $http use for sending get, put, post and delete kind of request 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 page.

index.html

HTML
    <!DOCTYPE html>
<html ng-app="testModule">
<head>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/js/Script.js"></script>
    <title></title>
    <meta charset="utf-8" />
</head>
<body>
    <div ng-controller="testController">
        <table border="1">
            <thead>
                <tr>
                    <th>
                        Student Id
                    </th>
                    <th>
                        Name
                    </th>
                    <th>
                        Address
                    </th>
                    <th>
                        Email
                    </th>
                    <th>
                        Phone
                    </th>
                </tr>
            </thead>
            <tr ng-repeat="s in students">
                <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>

In the above code, I use ng-repeat directive. With the use of this directive, we can call list wise information, so we have scope variable students, so I use ng-repeat='s in students' so this will give me all the related object data one by one. You can see that I use ng-repeat <tr> section because we want data row wise, so every time ng-repeat loop runs, this will create new <tr> row with data.

Now, it is time to check the output.

As you can see, finally our data is consumed by webapi. we can see all students data row by row through ng-repeat.
If you have any queries regarding this tip or if you have any suggestions, please post your valuable comments.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


Comments and Discussions

 
SuggestionMissed steps Pin
Member 1360857912-Jan-18 3:43
MemberMember 1360857912-Jan-18 3:43 
QuestionGet art. however I get an error Pin
Member 127036541-Nov-16 7:48
MemberMember 127036541-Nov-16 7:48 
Question[Problem] Cannot find Index Pin
Member 1149126914-Oct-16 3:48
MemberMember 1149126914-Oct-16 3:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.