在Angular服务中,我创建了以下函数:
getListKey(user) {
firebase.database().ref(`userprofile/${user.uid}/list`).once('value').then(snapshot => {
console.log(snapshot.val())
this.listKey = snapshot.val()
return this.listKey
})
}
我希望在加载时在另一个文件中调用此函数,并将返回的值赋给服务中的全局listKey
变量,以用于组件中的另一个函数。但是,即使使用async
/await
,第二个函数也会在检索数据之前触发。
这是我的组件中的相关部分:
this.afAuth.authState.subscribe(async (user: firebase.User) => {
await this.fire.getListKey(user);
this.fire.getUserList(this.fire.listKey).subscribe(lists => {...})
...
}
如何让getUserList()
等待listKey
发布于 2019-05-27 00:12:33
向getListKey添加return语句以返回promise。否则,您将返回undefined,并且等待undefined将不会等待数据库快照准备就绪。
getListKey(user) {
return firebase.database().ref(`userprofile/${user.uid}/list`).once('value').then(snapshot => {
console.log(snapshot.val())
this.listKey = snapshot.val()
return this.listKey
})
}
另外,你可能想在等待的时候放在左边:
this.afAuth.authState.subscribe(async (user: firebase.User) => {
const listKey = await this.fire.getListKey(user);
this.fire.getUserList(listKey).subscribe(lists => {...})
...
}
https://stackoverflow.com/questions/56318295
复制