AngularJS duplicates http requests

2019-05-11 08:49发布

问题:

I'm doing some interfaces with AngularJS and watching the Chrome Console I detect that each http request to an API it makes for duplicate. Is there any way to avoid this?

This is my simplified code

$http.jsonp('http://APIURL.com/api/category/menu?callback=JSON_CALLBACK').success(function(data){
    $scope.categories=data.categories;
});

Full code:

var kbControllers = angular.module('kbControllers', []);
kbControllers.controller("KBHomeController", function ($scope, $http, $rootScope) {
    $rootScope.header = 'Title of page';
    $http.jsonp('apicall.com/api/category/menu?callback=JSON_CALLBACK').success(function (data) {
        $scope.categories = data.categories;
    });
});

and this is my console

any thought?

回答1:

i have faced this problem, and you can resolve it like this :

  • check if you have declared ng-controller twice , you need to declare it just one time
  • check if you have declared data-ng-click , if so , you need to replace it with ng-click

that's it



回答2:

This is app.js

var app = angular.module('app', [
   'ngRoute','kbControllers', 'kbFilters', 'kbDirectives', 'angularytics', 'kbServices'
]).config(['$routeProvider', function($routeProvider) {
$routeProvider
    .when('/',
        {
            templateUrl: '/assets/angular/kb/partials/home.html',
            controller: 'KBHomeController'
        }
    ).when('/category/:category',
        {
            templateUrl: '/assets/angular/kb/partials/category.html',
            controller: 'KBCategoryController'
        }
    )
    .otherwise({redirectTo:"/"});
  }
])

And in controllers.js

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

kbControllers.controller("KBHomeController", function ($scope, $http, $rootScope, Menu) {
$rootScope.header = 'Atención al cliente - Movistar Argentina';

    $http.jsonp('http://APIURL.com/api/category/menu?callback=JSON_CALLBACK').success(function(data){
    $scope.categories=data.categories;
    });
})

and my view /partials/home.html

[...]
<li ng-repeat="category in categories"><a href="#/category/{{category.path}}"><i class="{{category.icon}}"></i><span>{{category.name}}</span></a></li>
[...]