【发布时间】:2018-06-09 23:43:17
【问题描述】:
我在使用 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() 方法不起作用?
这是正常行为吗?难道我做错了什么 ?让我知道:-)
【问题讨论】:
-
嗨,我认为您的问题是 .then((client: any) => {key: clientId, name: client.name});行,因为你正在履行承诺
-
你好@federicoscamuzzi thx 为你的回答,但如果我不使用 then() 的承诺,我的代码只是在
const client = await this.getClient(this.id);之后停止即使 console.log(client) 也不会触发:x
标签: angular async-await angularfire2 angular2-observables