【问题标题】:AngularJS: - ngRoute and Controller http GET request causing infinite loopAngularJS:-ngRoute 和控制器 http GET 请求导致无限循环
【发布时间】:2015-10-28 02:15:32
【问题描述】:

我正在学习 AngularJS 网站上的教程,但遇到了问题。我尝试使用 console.log() 和警报自己调试问题。似乎有关 http 请求的某些内容导致它在无限循环中调用 ngRoute 指令。

我读过一些其他帖子说这是因为服务器返回 index.html 作为对 http 请求的响应。我认为这是我的问题,但我不确定如何检查我的 GET 请求返回的内容。

如何测试返回的内容并防止这种无限循环?

main.js 内容

var coffeeBeanApp = angular.module('coffeeBeanApp', [
    'ngRoute',
    'coffeeBeanControllers'
    ]);

coffeeBeanApp.config(['$routeProvider', function($routeProvider)
    {
        $routeProvider.
    when('/coffee', {
        templateUrl: 'partials/coffee-list.html',
        controller: 'CoffeeListCtrl'
    }).
    when('/coffee/:slug', {
        templateUrl: 'partials/coffee-detail.html',
        controller: 'CoffeeDetailCtrl'
    }).
    otherwise({
        redirectTo: '/coffee'
    });
}]);

controllers.js

var coffeeBeanControllers = angular.module('coffeeBeanControllers', []);

coffeeBeanControllers.controller('CoffeeListCtrl', function ($scope, $http) {
        $http.get('/api/coffee').success(function(data){$scope.beans = data;})
});

coffeeBeanControllers.controller('CoffeeDetailCtrl',
    ['$scope', '$routeParams', function($scope, $routeParams){
        $scope.slug = $routeParams.slug;
    }]);

【问题讨论】:

    标签: javascript angularjs ngroute


    【解决方案1】:

    试试这个以获得更好的调试:

    $http.get('/api/coffee').then((function successCallback(response) {
           // this callback will be called asynchronously
           // when the response is available
           console.log(response); 
    }, function errorCallback(response) {
           // called asynchronously if an error occurs
           // or server returns response with an error status.
           console.log(response);
    });
    

    或者你可以在你的成功回调中加入一个console.log(在https://docs.angularjs.org/api/ng/service/$http中用红色标记为弃用)

     $http.get('/api/coffee').success(function(data){console.log(data);});
    

    【讨论】:

    • 谢谢mentat。现在已经彻底阅读了文档并发现了已弃用的“成功”方法,这很有意义。我仍然有一个问题。即使使用了 console.log 和回调,我仍然得到引用循环,它阻止任何值被记录到控制台。知道是什么导致了这种循环行为吗?
    • 您确定您的 http 调用是问题所在吗?也许您可以注释掉并查看行为如何变化。你能分享你得到的实际错误信息吗?
    • mentat,你说得很对。我的http调用不是问题。我将它自己移到了一个控制器中,它工作得很好。我认为 ngRoute 导致了这个问题。它似乎在调用 index.html 不断地将我的应用程序的多个实例相互嵌套。知道是什么原因造成的吗?
    猜你喜欢
    • 1970-01-01
    • 2015-08-30
    • 2017-10-17
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 2019-04-25
    • 2011-07-31
    相关资源
    最近更新 更多