Google+

Thursday, March 31, 2016

#14 - Make GET Requests with pagination to OData Web API RESTful service using $http AngularJS

In this article we review how to Make GET Requests to an OData Web API RESTful service using $http AngularJS,  by developing in 15 minutes an Angular Application that includes a Controller with an $http service dependency, to fetch data from a REST OData web service , loading a paginated list of products.
You can learn this step-by-step tutorial as a standalone, or you can see the previous lessons of the series. This is the Lesson #14 in the "AngularJS: From 0 To 100" articles written for Beginners. This lessons start at Lesson #1   .
This App can be downloaded from the following GitHub repository:
https://github.com/CarmelSoftware/AngularJS_OData_HTTPGET


<<<<  PREVIOUS LESSON               NEXT LESSON >>>>


In this tutorial we're using the "Brackets" open source web Editor , which supports AngularJS Apps, and you can read more about it in this post.

This is the AngularJS App that we'll develop here from scratch :

How to Debug AngularJS Apps with the free Batarang Debugger      14


Make GET Requests with pagination to OData Web API RESTful service using $http AngularJS


You can download this entire App from the following URL:
https://github.com/CarmelSoftware/AngularJS_OData_HTTPGET/archive/master.zip

First, let's add the references to the AngularJS javascript framework using CDN, and defining the HTML5 file as an data-ng-app Angular App:





How to Debug AngularJS Apps with the free Batarang Debugger



(get the source code):

<!doctype html>
<html data-ng-app="OrchidsApp">
<head>
<title>
    AngularJS HTTP GET
</title>
     
    <link href="Style.css" rel="stylesheet" type="text/css"  />
    <script  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
    <script src="Controllers.js" type="text/javascript"></script>
</head>


Next, copy-paste the following CSS3 style to your style.css file:

body {background:rgba(255, 238, 238, 0.5);
}
img {width:100px;height:100px;
}
div[id^=controls] , input[type=number]
{
padding:5px 5px 5px 25px;
margin:10px 15px 15px 25px;
font:900 12px Comic Sans MS;
opacity:0.9;
background:#fed;    
border:10px solid #ddd;    
border-radius: 10px;
box-shadow:10px 10px 2px #c0c0c0;
}
button
{
padding:5px 5px 5px 5px;
margin:10px 15px 15px 15px;
width:120px;
text-align: center;
background:#ddd; 
font:900 14px Comic Sans MS;
opacity:0.9;
border:1px solid #c0c0c0;    
border-radius: 10px;
box-shadow:10px 10px 2px #c0c0c0;
}
ul
{
list-style:none;    
}
.centered
{
 text-align:center;   
}
.angular
{
padding:5px 5px 5px 5px;
margin:25px 15px 15px 25px;
width:350px;
text-align:center;
background:#fee; 
font:900 14px Comic Sans MS;
opacity:0.9;
border:1px solid #c0c0c0;    
border-radius: 10px;
box-shadow:10px 10px 2px #faf;
}
.title {
    width: 90%;
    border: solid 1px #fea;
}


Add a <div> bound to an data-ng-controller:

How to Debug AngularJS Apps with the free Batarang Debugger       1



(get the source code):
<body class="centered">
<div class="angular | title" >                  
   <h1>Orchids AngularJS App</h1>     
    <h2>List of my Favorite Orchids</h2>  
</div>      
    <div id="controls1" data-ng-controller="OrchidsCtl"> 


Create a javascript Controller.js file, and add a module with a Controller:

How to Debug AngularJS Apps with the free Batarang Debugger      2

Notice we did a Dependency Injection for three services : $scope, to work with variables, $http for sending HTTP requests to the web server, and $log for making it easy to debug our app.

(get the source code):

var oOrchidsApp = angular.module('OrchidsApp', []);

oOrchidsApp.controller('OrchidsCtl', ['$scope', '$http', '$log', function ($scope, $http, $log) {

    $scope.angularClass = "angular";
    $scope.OrchidsList = [];


At the HTML5 file, add a list and use the data-ng-repeat directive, for displaying the "Orchid" items when loaded from the OData web service:

How to Debug AngularJS Apps with the free Batarang Debugger      3



(get the source code):

<ul >                
            <li data-ng-repeat="Orchid in OrchidsList">   
                 <div data-ng-class="angularClass" >                         
                        
                 <img src="Images/{{Orchid.MainPicture}}" alt="{{Orchid.Title}}"  > <br />           
                    <span >{{Orchid.BlogID}}  .  {{Orchid.Title | uppercase}} <br />
                            {{Orchid.Text}}   {{Orchid.DatePosted | date }}
                    </span>  
                 </div>
            </li>             
        </ul>        


We thoroughly  explained using AngularJS collections in this previous lesson .
The difference is, now we're going to fetch the data from an OData RESTful  web service, using an Ajax enabled AngularJS Service called $http. This service provide also another kinds of HTTP requests like POST, PUT etc. Here we only need to use the HTTP GET verb.
More info about the $http AngularJS service can be found at the Angular official web site:

How to Debug AngularJS Apps with the free Batarang Debugger        17


So let's use the $http get() method service as follows:

How to Debug AngularJS Apps with the free Batarang Debugger      4



(get the source code):


$scope.fnShowOrchids = function (direction) {

       
        $http.get(sURL).success(function (response) {

            $scope.OrchidsList = response;
            $log.info("OK");

        },

         function (err) { $log.error(err) })
    }

You can see that we concatenate this get() method with another "success" method, a callback which  gets two functions as parameters: the first is the callback called when everything's fine, and the second is for when something went wrong.
Inside the method, we just load the "OrchidsList" with the data returned by the HTTP response.
Now , we need a REST OData web service, which in my case is the following:

How to Debug AngularJS Apps with the free Batarang Debugger      10

In case that you don't have an OData RESTful web service on your project, i developed one that you can use, in this URL:

http://carmelwebapi.somee.com/WebAPI/OrchidsWebAPI

This OData RESTful service is exactly the same as described in this tutorial. You can use it at your own.
An example of using this OData Web API:
http://carmelwebapi.somee.com/WebAPI/OrchidsWebAPI/?$skip=2&$top=3


Now , about Pagination. We don't want all the data to be displayed on the web page, so we use the built in OData pagination capabilities. The OData service supports a "skip" and a "top" parameters, for example, this snapshot shows skipping 2 orchids blog posts, and displaying the top 3 items:

How to Debug AngularJS Apps with the free Batarang Debugger    11

In other words, in this example the Page has 3 items, and we just skipped 2 other ones.
To produce the pagination, we add two buttons that call a Controller's method "fnShowOrchids", telling it to display 1 previous page  (-1) and 1 next page (1):



How to Debug AngularJS Apps with the free Batarang Debugger        5



(get the source code):

<div class="centered"> 
            
            <button data-ng-click="fnShowOrchids(-1)"><<<<</button>
           
            <button data-ng-click="fnShowOrchids(1)">>>>></button>
            
        </div> 


At the Controller, we should add the Page size and the Current page variables, and calculate which page claim from the web server:

How to Debug AngularJS Apps with the free Batarang Debugger    6



(get the source code):

 $scope.pageSize = 2;

 var iCurrentPage = -1;

$scope.fnShowOrchids = function (direction) {

        iCurrentPage = iCurrentPage + direction;
        iCurrentPage = iCurrentPage >= 0 ? iCurrentPage : 0;
        
        var sURL = "http://localhost:21435/WebAPI/OrchidsWebAPI/" +
            "?$skip=" +
            iCurrentPage * $scope.pageSize
            + "&$top="
            $scope.pageSize;


        $http.get(sURL).success(function (response) {

            $scope.OrchidsList = response;
            $log.info("OK");

        },

         function (err) { $log.error(err) })
    }

We build the URL , and send the current Page and also the its size :

How to Debug AngularJS Apps with the free Batarang Debugger    7




We made the page size an $scope variable, a part of the Model, in order to allow the user to modify its size, using the following HTML5 input number element:

How to Debug AngularJS Apps with the free Batarang Debugger       8



(get the source code):

 <input type="number" data-ng-model="pageSize" max="4" min="1" value="2" />

Then the $scope.pageSize allows us to calculate the "skip" and "top" values:

How to Debug AngularJS Apps with the free Batarang Debugger      9



We're done with the code. Now, run the app to get this web page:




How to Debug AngularJS Apps with the free Batarang Debugger     12

Click the NEXT (>>>) button and see the data fetched from the OData service:


How to Debug AngularJS Apps with the free Batarang Debugger       13


The page size is "2" by default, as we instantiated it at the Controller:

How to Debug AngularJS Apps with the free Batarang Debugger      14

Now, let's change the page size:


How to Debug AngularJS Apps with the free Batarang Debugger       15


As you see, now the page size is 1:

How to Debug AngularJS Apps with the free Batarang Debugger       16

Remember to use the $log functionality to send to yourself messages , easing to debug the AngularJS app.

That's All!!! You have begun making GET Requests with pagination to OData Web API RESTful service using $http AngularJS with Dependency Injection . In the next article we will continue to learn Step by Step about  making post requests to an odata web api restful service using the $http  angularjs . 
Enjoy AngularJS.....

      by Carmel Schvartzman


<<<<  PREVIOUS LESSON             NEXT LESSON >>>>



כתב: כרמל שוורצמן

No comments:

Post a Comment