AngularJS Tutorial - 2, APIs

In this part we will call an API to fill a list through a button.

Screenshot

Download

The source for this part is here: 02_apis.zip.

The samples can be run with Firefox, in general or by running, into the directory,

Http Service

To make http queries to services a dependency should be added to our controller: $http.

Real usage

It contains two methods:

The two functions returns a promise that can handle error and succes, with specific callback functions taking the following parameters

for example:

    $http.get('http://test/com')
    success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
    }).
    error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
    });

The API we will be using

In our test, since we don't have any webservice available we will use a "fake" rest server. It's composed by several parts (that must all be included!):

Look at the notes to see how it works

The API exposed actually respond to GET requests to the url '/customers' The object returned contains:

Show me the data!

Setting up the controller

We will include sinon-server, fakerest and api-server to let the APIs work Then angular.min and the bootstrap.css file to have a nicer style!

We will create a new application with its controller. The controller, when loading will create an empty array of customers. Then will declare a function that will call the "/customers" API retrieving its data and filling the customers array.

The get function will return asynchronously and will invoke the success callback passing

var app = angular.module('customersModule',[]);

app.controller('CustomersController',['$scope','$http',function($scope,$http){
    $scope.customers = [];
    
    $scope.loadData = function(){
        $http.get(/customers)
            .success(function(data, status, headers, config) {
                $scope.customers=data;
            });
    }
}]);

Preparing the visualization

We will set the body with the right module and the controller. Then we will create a button. The buttons contains the ng-clik attribute. The function called on the ng-click atribute will be a function inserted on the $scope by the CustomersController.

A "template" is present to iterate on the all customers. This is declared through the "ng-repeat" attribute (an Angular directive)

Then all the data inside a single customer is shown

    <body ng-app="customersModule">
        <div ng-controller="CustomersController">
            <button type="button" class="btn btn-default" ng-click="loadData()">Load</button>
            <table class="table">
                <tr><th>Id</th><th>First Name</th><th>Last Name</th></tr>
                <tr ng-repeat="customer in customers">
                    <td>{{customer.id}}</td><td>{{customer.first_name}}</td><td>{{customer.last_name}}</td>
                </tr>
            </table>
        </div>
    </body>

Clicking on the Load button the data will be...hem...loaded!

Notes

FakeRest

FakeRest uses a standard REST flavor, described below.

``` GET /books?filter={author_id:1}&sort=['title','desc']&range=[0-9]

HTTP 1.1 200 OK Content-Range: items 0-1/2 Content-Type: application/json [ { id: 3, authorid: 1, title: 'Sense and Sensibility' }, { id: 2, authorid: 1, title: 'Pride and Prejudice' } ] ```

``` POST /books { author_id: 1, title: 'Emma' }

HTTP 1.1 201 Created Location: /books/4 Content-Type: application/json { "author_id": 1, "title": "Emma", "id": 4 } ```

``` GET /books/2

HTTP 1.1 200 OK Content-Type: application/json { id: 2, author_id: 1, title: 'Pride and Prejudice' } ```


Last modified on: April 05, 2015