在我的應用程序中,我使用了兩個不同的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