在我的应用程序中,我使用了两个不同的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调用吗?或者我的代码需要更根本的改变?
为什么在getCatalog里面定义getService?你能解决这个问题吗? – mavarazy
也许在getCatalog()只返回$ http.get而不是$ http.get()。然后() – glcheetham
@mavarazy我把它们嵌套为getService依赖于getCatalog的结果。但是,我测试它们是非嵌套的,并得到了同样的问题。 – chrism202