我刚刚在使用 AngularFire2 Observables 时遇到了一个奇怪的问题,看看这段代码,然后告诉我你是否知道发生了什么:
async save(){
const client = await this.getClient(this.id);
console.log(client); // ZoneAwarePromise blah blah
}
getClient(clientId) {
return this.db.object('clients/' + clientId)
.valueChanges()
.toPromise()
.then((client: any) => {key: clientId, name: client.name});
}
所以这段代码不起作用,但如果我像下一个代码一样这样做,它就会起作用:
async save(){
const client = await this.getClient(this.id);
console.log(client); // {key: 'blah', name: 'fooblah'}
}
getClient(clientId) {
return new Promise((resolve, reject) => {
this.db.object('clients/' + clientId)
.valueChanges()
.subscribe((client: any) => resolve({key: clientId, name: client.name}));
}
那么,为什么创建 Promise 并解析 Observable 数据可以工作,而 .toPromise() 方法却不起作用呢?
这是正常行为吗?难道我做错了什么 ?让我知道:-)
最佳答案
它不起作用的原因是你的 promise 永远不会兑现。
为了实现您的 promise ,您的可观察需要完成
。
因此,如果您只需在 toPromise() 前面添加 take(1)
,您就会获得所需的效果:
return this.db.object('clients/' + clientId)
.valueChanges()
.take(1)
.toPromise();
关于angular - AngularFire2 toPromise() 方法的异步/等待不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48024194/