user3821263
user3821263

Reputation: 121

Angular.js and displaying Rest JSON

I'm a newbie to Angular and I'm doing some prototyping. Unfortunately when I call a REST service I'm having issues displaying the data. The console is not providing clues because no errors come back.

HTML is below:

<!doctype html>
<html ng-app="statViewer">
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>Test Angular Page</title>

    <script  src="js/angular.min.js" type="text/javascript"></script>
    <script  src="js/statViewer.js" type="text/javascript"></script>

</head>
<body ng-controller="MainController">

    <h1> {{title}} </h1>
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Total</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="stat in stats">
            <td>{{stat.MessageName}}</td>
            <td>{{stat.TypeCount}}</td>
        </tr>
    </tbody>
</table>


</body>
</html>

JS is below:

(function() {

    var app = angular.module("statViewer", []);

    var MainController = function($scope, $http) {

        $scope.title = "Angular test page";

        $http.get("http://localhost:8080/API/getstats.json")
            .then(onStatsComplete);

        var onStatsComplete = function(response)
        {
            $scope.stats = response.data;
        };


    };

    app.controller("MainController", MainController);

}()); 

I see that the service is being called because on the console window it prints out that the call was triggered. Result of the REST API being invoked is here:

[
    {
        "TypeCount": 45,
        "SentDate": "2014-08-20T00:00:00.000Z",
        "MessageName": "Message Type 1"
    }
]

Upvotes: 1

Views: 802

Answers (2)

Dilip Tirumala
Dilip Tirumala

Reputation: 371

To give more insight, when ever you do $http.get call.

Every $http call is Aysncronous in angularJs.

   $http.get("http://localhost:8080/API/getstats.json")
            .then(function(result){   
console.log(result.TypeCount);
               });

Let me know if you still unable to get the data.

Upvotes: 0

Miichi
Miichi

Reputation: 1799

You are defining the variable onStatsComplete with your callback function after the call to $http.get. So at the point in time when you are making the call to $http.get the value undefined is passed to then rather than your callback function. Swap the lines around like this:

    var onStatsComplete = function(response)
    {
        $scope.stats = response.data;
    };

    $http.get("http://localhost:8080/API/getstats.json")
        .then(onStatsComplete);

See also this question on the difference between writing var y = function(){...} and function y(){...}.

Upvotes: 2

Related Questions