Consuming Web API Services in AngularJs (Part 6)


Angularjs framework has inbuilt support for consuming external service via $http.get method in json format. There are so many approaches to consume the service.

In this post I will explain one of the most popular approaches to consume external service using Ajax request from WEB API as external Service.

Step 1: Create the blank asp.net MVC 5.0 application.

Step 2: Go to controller folder and right click and add Web API EmpController like given below image

Web API ADD

Step3: Write the code in EmpController like this




using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI_Sample.Models;
using System.Data;
using System.Data.SqlClient;

namespace WebAPI_Sample.Controllers
{
    public class EmpController : ApiController
    { 
      
       [HttpGet]
       public List<Emp> GetEmpDetails()
        {
            List<Emp> Emps = new List<Emp>();
            using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True"))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand("Select * from tblEmp", con))
                {
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        Emp objEmp = new Emp();
                        objEmp.Id = Convert.ToInt32(dr["Id"]);
                        objEmp.EmpName = dr["EmpName"].ToString();
                        objEmp.EmpAddress = dr["EmpAddress"].ToString();
                        objEmp.EmpSal = Convert.ToDecimal(dr["EmpSalary"]);
                        Emps.Add(objEmp);
                    }
                    return Emps;
                }
            }
        }

    }
}

Note: Make ensure that there is table I.e tblEmp in your database with Id, EmpName, EmpAddress, EmpSalary field and there should be some dummy data.

Step 4: Now build the application and make ensure that service is working as per as expected. For this you to click F5. Then you will get forbidden error message like this.

Forbidden_Error

Step 5: Now change the URL path like this to execute the Web Api Code

http://localhost:51808/api/Emp/GetEmpDetails

URL Change

Then you will get the data in xml format from Web api service like above image.

Step 6: Write the http get request to consume web api service in angularJs in plain HTML page like given below code




<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="../Scripts/angular.min.js"></script>
    <style>
        table, th, td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
        }

            table tr:nth-child(odd) {
                background-color: #f1f1f1;
            }

            table tr:nth-child(even) {
                background-color: #ffffff;
            }
    </style>
    <meta charset="utf-8" />
</head>

<body>
    <fieldset>
        <legend>
            <b> Demo application to consume WEB API in AngualarJs</b>
        </legend>

            <div ng-app="myApp" ng-controller="EmpController">

                <table>
                    <thead>
                        <tr>
                            <th>Emp ID</th>
                            <th>EmpName</th>
                            <th>EmpAddress</th>
                            <th>EmpSal</th>
                        </tr>
                    </thead>
                    <tr ng-repeat="x in EmpNames">
                        <td>{{ x.Id }}</td>
                        <td>{{ x.EmpName }}</td>
                        <td>{{ x.EmpAddress }}</td>
                        <td>{{ x.EmpSal }}</td>
                    </tr>
                </table>

            </div>
       
    </fieldset>
    <script>
        //This is the Module in angular
        var app = angular.module('myApp', []);

        // This is the controller in angular
        app.controller('EmpController', function ($scope, $http) {
            $http.get("http://localhost:51808/api/Emp/GetEmpDetails")
           .success(function (response) {
               $scope.EmpNames = response;
           });

        });
    </script>

</body>

</html>

Step 7: Now run the HTML file and you will get out put like this

FinalOP

Summary:

In this article we learnt that how to create Wep API Service and how to consume it in AngularJs.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: