Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS calls HTTP multiple times in controller

I am developing a page with Angular, and have an init() method in my controller. The code is as follows:

var filtersController = ['$scope', '$http', function ($scope, $http) {
    $scope.init = function () {
        $http({
            method: 'GET',
            url: '/json-tags-test',
            cache: true
        }).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.
        });
   };
}];

It is just a call to a simple JSON file.

My HTML is as follows:

<div class="container main-frame" ng-app="projectsApp" ng-controller="filtersController" ng-init="init()">
</div>

For some reason, this get call gets call twice every time I load the page. Is this standard behaviour?

Many thanks,

Dash

enter image description here

like image 866
iamdash Avatar asked Jul 31 '13 10:07

iamdash


1 Answers

I don't think it is getting called twice, i just created a plunk for you to see this.

var app = angular.module('projectsApp', []);
app.controller('filtersController', ['$scope', '$http', function ($scope, $http) {
  $scope.status = 'Page loading';
  var count = 0;
    $scope.init = function () {
      $scope.status = 'API called';
        $http({
            method: 'GET',
            url: '/json-tags-test',
            cache: true
        }).success(function (data, status, headers, config) {
                // this callback will be called asynchronously
                // when the response is available
            console.log('success');
            count++;
            $scope.status = 'successful: '+ count;
        }).error(function (data, status, headers, config) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
            console.log('error');
            count++;
            $scope.status = 'failed times: '+ count;
        });
   };
}]);

XHR logs from DEV tools

Network console only one HTTP call

Edit:

Updated plunk with a dummy json file

http://plnkr.co/edit/hTdtLK?p=preview

Same seen in logs

As you can see once again that its getting called only once. Clear the logs i guess you are seeing the logs for the previous page load, coz changes are immediately visible when in preview mode.

like image 193
Abhishek Nandi Avatar answered Sep 25 '22 00:09

Abhishek Nandi