2016-09-28 37 views
-1

在我的AngularJS應用程序中,我有一個Service和多個controllers一次運行。應用程序在Angular Service中從服務器接收數據更新(以JSON的形式)。我需要在服務器中排列這些數據(因爲數據量很大),然後在某些處理服務需要使用註冊了服務的控制器回調函數將此數據發送到所有控制器。控制器進一步處理這些數據。AngularJS如何使用Promise處理數據隊列

我具有低於JSON對象的隊列:

In ----> [Obj1] - [Obj2] - [Obj3] - [Obj4] ---> OUT 

輸入操作是異步的並且有在隊列中的每個第二(隊列也可以成爲是空的)獲取添加對象的「n」個號碼。

我需要一次彈出一個項目,然後處理接收到的JSON數據,這個過程會一直持續到隊列中的最後一個項目。當新項目被添加到他們將要處理的隊列中時也是如此。

從一些帖子我知道這可以使用AngularJS Promise完成,但是因爲我對Angular完全陌生,所以我無法理解它是如何實現的。

此外,在一些例子中提到使用var deferred = $q.defer();,因此如何使用$q是什麼$qPromise區別?

還有其他「簡單」的方式來實現此功能?

示例代碼:

angular.module('myApp') 
.service('DataService', ['$rootScope', 'UpdateService', function($rootScope, UpdateService) 
{ 
    // To store array of JSON updates  
    var arrayOfUpdates = []; 

    // To store callbacks to which we need to send updates after processing 
    var arrayofCallbacks = []; 

    // Method is getting called when there are updates from "UpdateService" server 
    this.onDataUpdated = function (jsonObj) 
    { 
     // This will add this object in the array 
     arrayOfUpdates.unshift(jsonObj); 
    } 

    // This method will process data and send it further 
    function processData() 
    { 
     // Get the last element from the array 
     var jsonObj = arrayOfUpdates.pop(); 

     // Now process this JSON data - this method takes time 400-500 MS 
     var data = doSomeCalculations(jsonObj); 

     // There can be 10-20 callbacks at a time -- This also takes time 
     for(var index=0;index<arrayofCallbacks.length;index++) 
     { 
       var object = arrayofCallbacks[index]; 
       object.onUpdatedData(data); 
     }  

     // After processing this item 
     // Pop next element and process and send to registered callbacks 
     // I can not call "processData()" again as it can create loop 
     // Also calling it after interval (using $interval) might call it when it has not completed processing 
    } 
}); 

回答

1

你可以看看角事件。 Working with $scope.$emit and $scope.$on

訂閱在每個控制器和數據處理後發佈所有控制器然後將處理的事件。

+0

是的我可以使用$ emit和$ on從服務發送和接收事件到控制器。但是有更好的實施方式嗎?還有如何有效排放會有丟失/跳過和事件的機會,因爲每秒服務需要發送很多事件。 – User7723337

+0

不存在丟失或跳過的現實變化。而且沒有辦法說什麼是更好的方法,因爲我不知道你的要求。你的意思是更快,不那麼複雜/代碼行,更可維護/可讀。 此外,你可能不會得到什麼更好的答案,因爲這主要是基於意見,這是不允許在stackoverflow上。 –

+0

在我的意見中使用事件更好,因爲你不必自己保留一個回調列表。這將通過角度來處理。 –