KDC
KDC

Reputation: 1471

$http.get keeps launching new queries

I'm encountering a weird issue in my AngularJS app. It's supposed to access a number of values from a cookie 'login', pass those values to an API endpoint and then return the API response. This works fine, except it keeps launching new GET queries continuously every 500ms. This results in an unending stream of the console error: "Error: 10 $digest() iterations reached. Aborting!" and forcing me to kill it manually.

Where is this weird behavior coming from, and how can I limit it to just 1 run?

workbooks.html

<body>
<div>This is the workbooks view.</div>
<span>{{callQueryWorkbooksForUser()}}</span>
<section ui-view>{{response}}</section>
</body>

workbooks.controller.js

'use strict';
(function() {

  class WorkbooksComponent {
    constructor($scope, $http, $cookies) {
      $scope.callQueryWorkbooksForUser = function() {
        var login = JSON.parse($cookies.get('login'))
        var auth_token = login.authentication_token;
        var siteid = login.site_id;
        var userid = login.user_id;

        $http({
          method: 'GET',
          url: '/api/sites/' + siteid + '/users/' + userid + '/workbooks',
          params: {
            auth_token: auth_token
          }
        }).then(function successCallback(response) {
          $scope.response = response.data
        }, function errorCallback(response) {
          $scope.response = 'Server error'
        });

      };

    }
  }

  angular.module('orbitApp')
    .component('workbooks', {
      templateUrl: 'app/workbooks/workbooks.html',
      controller: WorkbooksComponent
    });

})();

Upvotes: 0

Views: 33

Answers (1)

Muthukannan Kanniappan
Muthukannan Kanniappan

Reputation: 2079

Make the http request in init block of your controller.

  class WorkbooksComponent {
    constructor($scope, $http, $cookies) {

        this.$onInit = function() {
            var login = JSON.parse($cookies.get('login'))
            var auth_token = login.authentication_token;
            var siteid = login.site_id;
            var userid = login.user_id;

            $http({
              method: 'GET',
              url: '/api/sites/' + siteid + '/users/' + userid + '/workbooks',
              params: {
                auth_token: auth_token
              }
            }).then(function successCallback(response) {
              $scope.response = response.data
            }, function errorCallback(response) {
              $scope.response = 'Server error'
            });
        };

    }
  }

Upvotes: 1

Related Questions