AngularJS的控制器调用HTTP多次 [英] AngularJS calls HTTP multiple times in controller

查看:205
本文介绍了AngularJS的控制器调用HTTP多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发展与角一个页面,并在我的控制器的init()方法。在code是如下:

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

这仅仅是一个简单的JSON文件的调用。

It is just a call to a simple JSON file.

我的HTML如下:

<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?

非常感谢,

短跑

推荐答案

这问题也可以由具有NG-应用与路由控制器并在页面中的NG-控制器参考引起的。例如,如果你的应用程序是这样的:

This problem may also be caused by having an ng-app with routing to your controller and an ng-controller reference in your page. For example, if your app looks like:

<html lang="en" ng-app="myApp">
<head>...</head>
<body>
<div ng-controller="myController">
...
</div>
</body>
</html>

定义的Javascript应用程序:

Javascript defining the app:

angular.module('myApp',[]) {
$routeProvider.when('/path', {templateUrl: '...', controller: myController);

在上面的例子中,与定义的路由myController的,控制器将被实例化两次,你会看到所描述的两个电话。

In the case above, with the defined routing to myController, the controller will be instantiated twice and you'll see two calls as described.

更新

以上code描述什么是问题,但什么是正确的解决方案,缺少所以我更新的答案,每@Intrepid评论。

Above code describe what is problem but what is proper solution is missing so I updated answer as per @Intrepid comment.

需要删除 NG-控制器=myController的从如果你已经路线定义你的HTML模板。

Need to remove ng-controller="myController" from your html template if you already defined in route.

这篇关于AngularJS的控制器调用HTTP多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆