1

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"
    }
]

2 Answers 2

2

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(){...}.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.