在 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
?
向 getListKey 添加 return 语句以返回承诺。否则,您将返回 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 => {...})
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句