AngularJS:异步$ http.get调用导致View出现问题

时间:2016-03-02 18:41:15

标签: javascript angularjs json

在我的应用程序中,我正在使用两个不同的API调用 - 第一个提取服务目录及其唯一ID,然后,一旦我拥有ID,我就会提取该服务的定价。但是我遇到的问题是第二个GET请求每页加载数百次,并导致Chrome和Linux中出现内存问题。 Firefox浏览器。

在我看来,我有以下内容;

<tr ng-repeat="c in catalog track by $index">
    <td>{{ c.id }}</td> 
    <td>{{ c.name }}</td> 
    <td>{{ c.description }}</td> 
    <td>{{ c.service_status }}</td> 
    <td>{{ getService(c.id) }} {{services}} </td>  
</tr>

我的两个“API调用”(简称如下)在工厂和工厂中。使用承诺如下;

app.factory('catalogDataFactory', function($http){
    var getCatalog = function() {
    // next line is the result of an API call for testing purposes
        return $http.get("../data/catalog.json").then(function (result){
            return result.data;
        });
    };
    return { getCatalog: getCatalog };
});



app.factory('servicesDataFactory', function($http){

    var service = {};
    var baseURL = '../data/'; 
    var _guid = '';

    service.setGuid = function(guid){
        console.log("setGuid is being called too many times with input: " + guid); // appears hundreds of times per minute
        _guid = guid;
    }

    service.callAPI = function(){
        console.log("callAPI is being called too many times"); // appears hundreds of times per minute
        return $http.get(baseURL + _guid + ".json").then(function (result){
                return result.data;
        });

    }

    return service;
});

我的控制器看起来像这样;

app.controller('customersCtrl', function($scope, $compile, catalogDataFactory, servicesDataFactory, utilities) {

    $scope.catalog = []
    $scope.service = [];

    catalogDataFactory.getCatalog().then(function(result) {
        $scope.catalog = result.data[0]['services'].data; // iterate through JSON to find data array
        console.log("getCatalog is being called too many times"); // called hundreds of times per minute
        $scope.getService = function (guid){
            console.log("getService is being called too many times"); // called hundreds of times per minute
            servicesDataFactory.setGuid(guid);
            // return servicesDataFactory.callAPI();
            $scope.service = servicesDataFactory.callAPI();
        };

    }); // end of catalog promise

}); // end of controller

我收到以下错误:https://docs.angularjs.org/error/$rootScope/infdig?p0=10&p1=%5B%5D我的浏览器冻结了。如果我事先打开,那么我可以看到错误增加(相同的错误数千次)和console.logs一遍又一遍地出现。

我的问题是......我应该使用服务(而不是工厂)进行第二次API调用吗?或者我的代码是否需要以更基本的方式进行更改?

1 个答案:

答案 0 :(得分:0)

首先,在ng-repeat中调用函数是一种不好的做法,因为每次$ digest循环都会调用getService。这将发生在任何范围更改或任何http回调上。也许这就是你接到这么多电话的原因。

我建议您不要使用getService方法,而是从服务器创建返回目录及其服务的字典,或者构建一个调用控制器的广告。然后在你重复你可以简单地从该字典中获取服务值。