$ http.get不断启动新查询

时间:2016-06-07 10:21:12

标签: angularjs http

我在AngularJS应用程序中遇到了一个奇怪的问题。它应该从cookie'login'访问许多值,将这些值传递给API端点,然后返回API响应。 这很好,除了它每500毫秒不断启动新的GET查询。这导致控制台错误的无休止流:“错误:10 $ digest()迭代达到。中止!”并强迫我手动杀死它。

这种奇怪的行为来自何处,如何将其限制为仅1次运行?

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
    });

})();

1 个答案:

答案 0 :(得分:1)

在控制器的init块中发出http请求。

  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'
            });
        };

    }
  }