2015-06-19 81 views
3

這是我今天早些時候發佈的一個問題的後續。我正在通過this book on using AngularJS with Firebase,這導致我發佈this question。我找到了一個解決方案,但我仍然不明白的是API Documentation for a $firebaseArray中的示例似乎並未將其作爲異步請求處理。數據請求有時是異步的

var list = $firebaseArray(new Firebase(URL)); 

// add an item 
list.$add({ foo: "bar" }).then(...); 

// remove an item 
list.$remove(2).then(...); 

// make the list available in the DOM 
$scope.list = list; 

此外,書籍中的示例似乎也同步處理請求。

# Service 
var buildingsUri = FIREBASE_URI + '/buildings'; 
var ref = new Firebase(buildingsUri); 
var buildings = $firebaseArray(ref); 

var getBuildings = function() { 
    return buildings; 
}; 

... 
# Controller 
$scope.buildings = syncArraySvc.getBuildings(); 

它是如何$scope.list在第一個例子,$scope.buildings在第二個例子中可以用數據來正確填充時,他們​​沒有檢查,以確保該請求已完成?

+0

我假設firebase正在返回$ q承諾。這些通常會在請求完成後更新爲包含結果。當摘要運行時,視圖將隨着所述數據更新。 –

+0

@KevinB我認爲我在追隨。根據[Angular的$ q服務的文檔](https://docs.angularjs.org/api/ng/service/$q),'$ firebaseArray()'必須包裝'then'和其他爲了返回所請求的數據而無需在客戶端代碼中進行回調,回調是否正確? – Shaun

+0

不,我很確定它只是返回一個$ q的承諾。可以肯定的是,你應該看到的不僅僅是你的數據。它不能只是更新var來包含別的東西,它仍然是它返回給你的任何基礎對象。 –

回答

0

$ add和$ remove方法返回promise。 $ firebaseArray()方法返回一個數組,其中添加了一些特殊的函數和屬性。 $ add或$ remove都不需要數據在本地加載或取決於數據的狀態,因此可以同步調用它們。當然,數據仍然是異步下載的。因此,舉例來說:

var list = $firebaseArray(new Firebase(URL)); 

// add an item 
list.$add({ foo: "bar" }).then(function(ref) { 
    console.log('added', ref.key()); 
}); 

// remove an item 
list.$remove(2).then(function(ref) { 
    console.log('removed', ref.key()); 
}); 

console.log('list current contains', list.length, 'items'); 

list.$loaded(function() { 
    console.log('after loading initial data, the list contains', list.length, 'items'); 
}); 

假設該列表包含在加載時10個項目,並且該列表是不是這個代碼執行時遠程更改,我們會看到類似以下的輸出:

list currently contains 0 items 
after loading initial state, the list contains 10 items 
added abc123 
removed xyz456 

另外,我會注意到這個代碼可能是多餘的。通常當我們看到類似這樣的代碼時,這是因爲開發人員試圖將Firebase轉變爲CRUD模型。您可以直接返回$ firebaseArray(),並使用現有的方法(如$ getRecord()等),而不是人爲地將API包裝到您的服務中。

+0

[在相關問題](http://stackoverflow.com/questions/30943734/angularfire-firebasearray-can-add-but-not-read),有人評論說,使用'console.log'來調試AngularFire數據不是一個好主意。我明白'$ add'和'$ remove'方法,因爲它們使用'.then'標準的promise語法。在你的例子中,你可以用'list'作爲'$ loaded',但是如果你將'list'分配給作用域,例如'$ scope.list = list',它會正確地呈現列表項。即使在賦值之後放置'console.log'也會返回一個空數組。這就是我沒有得到的。 – Shaun

+0

在本地下載數據之前它將爲空。另外,在1.1.0和1.1.1版本中使用$ extend時,$ loaded方法中存在一個錯誤。它在1.1.2中被修復 – Kato