2016-03-02 76 views
0

在我的应用程序中,我使用了两个不同的API调用 - 第一个调用服务目录和它们的唯一ID,然后,一旦我有了ID,该服务的定价。但是,我遇到的问题是,第二次GET请求每次页面加载时都会遇到数百次,并导致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调用吗?或者我的代码需要更根本的改变?

+2

为什么在getCatalog里面定义getService?你能解决这个问题吗? – mavarazy

+0

也许在getCatalog()只返回$ http.get而不是$ http.get()。然后() – glcheetham

+0

@mavarazy我把它们嵌套为getService依赖于getCatalog的结果。但是,我测试它们是非嵌套的,并得到了同样的问题。 – chrism202

回答

0

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

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

+0

今天我要试一试,因为它很有意义。值得注意的是,在ng-repeat中调用函数是不好的做法。 – chrism202

+0

原来我的问题稍微复杂一点,会添加一个答案。 – chrism202