julia
julia

Reputation: 452

$http.get returns a result only after page refresh in AngularJS

I have an application built on the MEAN stack, running on localhost. On a REST endpoint called /metrics offered by NodeJS, I am reading with $http.get the contents in order to display it in a view on frontend.

The first time I load the view in the browser:

METRICS Array[0]

After a refresh:

METRICS [Object, Object, Object, Object, Object, Object]

And the code:

parserCtrl.js

/*global angular */
(function () {
  'use strict';

  angular.module('angularApp.controllers')
    .controller('parserCtrl', ['$scope', '$http',  function($scope, $http) {        
       $http.get('/metrics')
        .success(function (data) {       
            $scope.metrics = data;     
            console.log("METRICS", $scope.metrics);         
        })   
    }]);
}());

And in view:

parser.html

 <div class="row" ng-if="metrics">
        <div class="col-xs-12">
            <h2 ng-if="metrics">Additional metrics: </h2>           
        </div>
  </div>

    <div class="row" ng-repeat="metric in metrics">
        <div class="col-xs-3" ng-if="metric.name === 'blank'">Blank node count</div>
        <div class="col-xs-9" ng-if="metric.name === 'blank'">{{metric.value}}</div>

        <div class="col-xs-3" ng-if="metric.name === 'literals'">Literals count</div>
        <div class="col-xs-9" ng-if="metric.name === 'literals'">{{metric.value}}</div>
    </div>

What could be the problem? Is there any other way to do the call in AngularJS so that to get data from a REST endpoint?

Cheers, Iulia

Upvotes: 0

Views: 959

Answers (2)

julia
julia

Reputation: 452

The problem was with Node.js. The /metrics were initialized using the function initEdges(). initEdges() was called in another function called /parser

Solution:

$http.get('/parser')
                .success(function (data) {                          
                            $scope.parser = data;                                                   
                  console.log("JAVA METRICS", $scope.parser);    
                    $http.get('/metrics').success(function (dataMetrics) {       
                     $scope.metrics = dataMetrics;     
                    console.log("RDFSTORE METRICS", $scope.metrics);         
                    }).error(function(data) {       
                      console.log("Could not get RDFSTORE metrics");
                    });
                  })

Upvotes: 1

user3707579
user3707579

Reputation:

Try to use $timeout

$http.get('/metrics')
.success(function (data) {
    $timeout(function(){
        $scope.metrics = data;
    }, 100);
    console.log("METRICS", $scope.metrics);
}) 

or

Maybe it about caching you can see it Caching $http requests in AngularJS

Upvotes: 0

Related Questions