Srikanth Technologies

Consuming Web API from AngularJS

In this blog, we will see the following :

This blog uses the following products and technologies.

Please note, blog Contacts Web API and jQuery Client shows how to access Web API using jQuery. This blog shows how to access Web API using AngularJS. Data binding and module ngResource of AngularJS make it more simpler than jQuery.

Creating Web API

First we create a new project for Web API. This project uses a single Web API Controller to manage contacts, which are stored in CONTACTS table in SQL Server database.

Follow the steps given below: As we have created required classes for LINQ to SQL and Web API, lets now move on to a simple HTML page that uses AngularJS to consume Web API.

AngularJS Client

Now we use AngularJS in HTML page to make Ajax calls to Web API. We specially use ngResource module and $resource object of AngularJS to access our Web API from a simple HTML page using Ajax calls.

Add Angular.js and Angular-resource.js scripts to Scripts folder in your project. You can either download them manually from AngularJS website or use Nuget to install them into your project. In case of Nuget Package Manager select the following packages to install.

As soon as you run client it displays contacts taken from Web API.

Client

NOTE: You have to change port number in the URL so that it points to your Web server port number or you may have to change complete URL if you are hosting Web API differently.

The following table shows the functionality of each button.

Button What it does?
Add Contact Makes a POST request to Web API to add a new contact
Update Contact Makes a PUT request to Web API to update an existing contact. First we need to click on Edit button in table to bring data in the row for editing.
Refresh Makes a GET request to Web API and displays the results in the table
Clear Details Clears all textboxes
Edit Copies the data in the current row to textboxes to enable user to edit details. Subsequently user can click on Update Contact to update details in the database by sending PUT request to Web API
Delete Takes confirmation from user and upon confirmation sends DELETE request to Web API to delete the contact in the current row.

Client.html

<!DOCTYPE html>
<html>
<head>
    <title>Contacts Client</title>
    <style>
        body {
            font-family : Verdana;
            font-size : 12pt;
        }
        .heading {
            color:white;
            font-weight : bold;
            background-color:red;
        }
        td {
            text-align : center;

        }
        .message {
            
            font-size:12pt;
            font-weight :bold;
        }
    </style>
    <script src="Scripts/angular.js"></script>
    <script src="Scripts/angular-resource.js"></script>
    <script>
        var contacts = angular.module("contacts", ['ngResource']); // this module depends on ngResource module

        var controller = function ($scope, $resource) {  // controller uses $resource, which is part of ngResource
            $scope.contact ={};
            $scope.getContacts = function() {
                var request = $resource("http://localhost:52723/api/Contacts");
                $scope.contacts = request.query();
            };
            
            $scope.addContact = function () {
                var request = $resource("http://localhost:52723/api/Contacts");
                request.save($scope.contact,   
                       function (data) {        // success function 
                           $scope.error = "Successfully Added Contact [" + $scope.contact.Name + "]";
                           $scope.contact = {};
                           $scope.getContacts();
                       }
                       ,
                       function (data) {       // error function
                           $scope.error = "Sorry! Could not add  contact [" + $scope.contact.name + "]";
                       }
                 );
            };

            $scope.deleteContact = function (name) {
                var res = confirm("Do you really want to delete contact [" + name + "]?");
                if (!res)
                    return;

                var request = $resource("http://localhost:52723/api/Contacts/:name");
                request.delete( { name : name },
                       function (data) {        // success function 
                           $scope.error = "Successfully Deleted Contact [" + name + "]";
                           $scope.getContacts(); // refresh
                       }
                       ,
                       function (data) {       // error function
                           $scope.error = "Sorry! Could not delete contact [" + name + "]";
                       }
                 );
            };


            $scope.updateContact = function () {
                
                // create a custom action with name update
                var request = $resource("http://localhost:52723/api/Contacts/:name",
                      { name : $scope.contact.Name },
                      { update : { method : 'put'} }
                      );
                // call custom action update to make PUT request 
                request.update( $scope.contact,
                      function (data) {        // success function 
                           $scope.error = "Successfully Updated Contact [" + $scope.contact.Name + "]";
                       }
                       ,
                       function (data) {       // error function
                           $scope.error = "Sorry! Could not update contact [" + $scope.contact.Name + "]";
                       }
                 );

                
            };

            $scope.editContact = function (name) {
                for (var idx in $scope.contacts) {
                    if ($scope.contacts[idx].Name == name) {
                        $scope.contact = $scope.contacts[idx];
                        return;
                    }
                }
            };

            $scope.clear = function () {
                $scope.contact = {};
                $scope.error = "";
            }

            // call getContacts() on load to get contacts displayed initially
            $scope.getContacts();
        };

        contacts.controller("ContactsController", controller);  // add Controller to Module
    </script>
</head>
<body ng-app="contacts">
    <div ng-controller="ContactsController">
        <h2>Contacts Manager</h2>
        <fieldset style="background-color: silver">
            Contact Name : <input type="text" ng-model="contact.Name" />
            Email Address : <input type="text" ng-model="contact.Email" size="30" />
            Mobile Number : <input type="text" ng-model="contact.Mobile" />
            <p />
            <input type="button" value="Update Contact" ng-click="updateContact()" />
            <input type="button" value="Add Contact" ng-click="addContact()" />
            <input type="button" value="Refresh" ng-click="getContacts()" />
            <input type="button" value="Clear Details" ng-click="clear()" />
            <span ng-bind="error" class="message"></span>
            <p />
        </fieldset>
      
        <fieldset>
            <legend>Contacts</legend>
            <table   style="width:100%; padding: 5pt">
                <tr class="heading">
                    <th>Name </th>
                    <th>Email Address</th>
                    <th>Mobile</th>
                    <th></th>
                </tr>
                <tr ng-repeat="contact in contacts">
                    <td>{{ contact.Name }}</td>
                    <td>{{ contact.Email }}</td>
                    <td>{{ contact.Mobile }}</td>
                    <td>
                       <button ng-click="editContact(contact.Name)">Edit</button>
                       <button ng-click="deleteContact(contact.Name)">Delete</button>

                    </td>
                </tr>
            </table>
        </fieldset>
    </div>
</body>
</html>