[英]Promise to array with PouchDB and AngularJs ng-repeat
我正在將PouchDB數據庫中的allDocs()讀取到AngularJS變量中:
var db = pouchService.db;
$scope.recordlist = db.allDocs({startkey: 'move_', endkey: 'move_\uffff', include_docs: true});
console.log($scope.recordlist);
我注意到它返回了一個promise,當我嘗試使用ng-repeat讀取數組(以及數組中對象的屬性)時,它實際上無法訪問結果,我想是因為它們是深深嵌套的。
<div class="row msf-row"
ng-repeat="record in recordlist | filter: shouldShow"
ng-class="{ 'msf-cancelled': record.cancelled, 'msf-commented' : record.comment}">
<div class="col-md-1">{{record.time}}</div>
</div>
有什么辦法可以將這個承諾變成一個簡單的對象數組?
我也已在應用程序中加載了LoDash,我不知道它是否有用。
在實現諾言之后分配數組(如果發生錯誤,則顯示錯誤):
$q.when(db.allDocs({startkey: 'move_', endkey: 'move_\uffff', include_docs: true}))
.then(function (recordlist) {
$scope.recordList = recordList;
console.log($scope.recordlist);
})
.catch(function (error) {
console.error(error);
});
更新:正如Matt在評論中指出的那樣,如果您不使用angular-pouch angular-pouchdb包裝器,則需要將操作包裝在$scope.$apply()
以觸發摘要周期或首先轉換promise與$q.when()
有角度的承諾。 我認為將promise轉換為角度promise還可以解決日志錯誤,但是您應該始終處理錯誤(向用戶顯示消息)。 您當然可以使用全局錯誤處理程序來執行此操作。
您正在做的是訪問諾言,而不是諾言的結果。 盡管allDocs
確實確實返回了承諾,但它不是有角度的承諾,因此,您還應該將承諾包裝在when
獲得實際的有角度的承諾。
var pouchPromise = db.allDocs({startkey: 'move_', endkey: 'move_\uffff', include_docs: true});
$q.when(pouchPromise).then(function(recordList){
$scope.recordList = recordList;
console.log($scope.recordlist);
});
我將閱讀諾言在這里如何運作的內容。
應當注意,實際的pouchDB文檔在此處概述了這種利用pouch的方法: http ://pouchdb.com/api.html
特別:
使用離子/角度? 您可以將PouchDB Promise包裝在$ q.when()中。 當PouchDB承諾解決后,這將通知Angular更新UI。
在處理非角度承諾的異步性質時,這將使您避免使用$scope.$apply()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.