簡體   English   中英

在AngularJS中同時顯示內容

[英]showing content in the same time in AngularJS

盡管我是Angular的初學者,但我不知道如何最好地解決這個問題。 想象一下,我有兩個互相欠錢的用戶,即“ A”和“ B”。

'A'有5筆交易,必須向'B'支付5000美元。 而“ B”有5萬筆交易,必須向“ A”支付100000美元。 在這一刻,我看到2筆交易,而不是1筆,我必須先做數學運算。 代碼如下:

$scope.charges = {};

totalChargeUserToFactory.query({
    id: null
}).$promise.then(function (data) {
    $scope.charges.to = data;
});

totalChargeUserFromFactory.query({
    id: null
}).$promise.then(function (data) {
    $scope.charges.from = data;
});

所以我決定更改它以解決我的問題:

$scope.charges = {};

totalChargeUserToFactory.query({
    id: null
}).$promise.then(function (data) {
    $scope.charges.to = data;

    totalChargeUserFromFactory.query({
        id: null
    }).$promise.then(function (data) {
        $scope.charges.from = data;

        for (var i = 0; i < $scope.charges.to.length; i++) {
            for (var j = 0; j < $scope.charges.from.length; j++) {
                if ($scope.charges.to[i].userFromId === $scope.charges.from[j].userToId) {
                    if ($scope.charges.to[i].charge < $scope.charges.from[j].charge) {
                        $scope.charges.from[j].charge = (parseFloat($scope.charges.from[j].charge)
                        - parseFloat($scope.charges.to[i].charge)).toFixed(2);
                        $scope.charges.to.splice(i, 1);
                        i--;
                    } else {
                        $scope.charges.to[i].charge = (parseFloat($scope.charges.to[i].charge)
                        - parseFloat($scope.charges.from[j].charge)).toFixed(2);
                        $scope.charges.from.splice(j, 1);
                        j--;
                    }
                }
            }
        }

    });
});

現在真正的問題出現了。 如此多的事務需要花費時間才能加載內容。 剛加載A時,B加載時間延長了2秒,然后才出現在屏幕上。 看起來不太好...您能給我一些避免這種情況的提示嗎? 基於此代碼? 我將不勝感激。

我在Google上尋找解決方案,但找不到任何令人滿意的結果,這直接影響了我的問題。

當兩個承諾都在$q.all()幫助下解決后,您可以使用初始設計並執行一些代碼。

$scope.charges = {};

var q1 = totalChargeUserToFactory.query({
    id: null
}).$promise.then(function (data) {
    $scope.charges.to = data;
    return data;
});

var q2 = totalChargeUserFromFactory.query({
    id: null
}).$promise.then(function (data) {
    $scope.charges.from = data;
    return data;
});

$q.all([q1, q2]).then(function(data) {
    // do math here
})

您可以使用$ q.all等待所有api調用完成后再顯示任何內容。

$q.all([
  totalChargeUserToFactory.query({
    id: null
  }),
  totalChargeUserFromFactory.query({
        id: null
  })
]).then(function(values) {   
     $scope.charges.to = values[0];
     $scope.charges.from = values[1];
   });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM