【发布时间】:2019-11-25 07:33:00
【问题描述】:
我正在从与 PouchDB 数据库连接的服务中加载一个数组。从那里我构建一个数组并将其返回给组件。
我的服务
getBooks() {
let ar:BibleBook[] = [];
this.db.allDocs({
include_docs: true
}).then(function (result) {
result.rows.map((row) => {
ar.push(row.doc);
ar.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
});
}).catch(function (err) {
console.log(err);
});
return ar;
}
我的组件
ngOnInit() {
this.bibleBooks = this.db.getBooks();
this.selectBibleBook(this.bibleBooks[0]);
}
问题:this.bibleBooks[0] 未定义,因为我的服务的答案在 300 毫秒后出现。我怎样才能等到this.bibleBooks 是一个有效的数组?
我不想与setTimeout() 合作。有更清洁的解决方案吗?
【问题讨论】:
-
您不必为
this.db.getBooks();发送await吗?我猜这是一个async请求 -
是的..但是浏览器似乎比第一行更早地调用了第二行..所以我得到了未定义..
-
@eleinad - 是的,这就是异步请求的本质。
标签: arrays angular typescript ionic-framework