2016-03-02 66 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