繁体   English   中英

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

[英]AngularJS: Asynchronous $http.get calls causing issues on View

在我的应用程序中,我使用了两个不同的API调用-第一个调用提取服务及其唯一ID的目录,然后,一旦获得ID,便提取该服务的价格。 但是我遇到的问题是,第二个GET请求在每次页面加载时被击中数百次,并且在Chrome和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调用”(以下简化)在工厂中,并且使用promise的方式如下;

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调用中使用服务(而不是工厂)吗? 还是需要以更基本的方式更改我的代码?

首先,从ng-repeat内调用函数是一种不好的做法,因为对getService的调用将在每个$ digest循环上进行。 任何范围更改或任何HTTP回调都将发生这种情况。 也许这就是为什么您接到这么多电话的原因。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM