【发布时间】:2021-07-03 12:12:21
【问题描述】:
我是 Firebase 和 Typrescript 的新手。我有以下问题:我想要实时数据库中的用户名。
getUsername(id){
var username
firebase.database().ref().child("users/"+id+"/username")
.once("value",snapshot => {
if (snapshot.exists()){
username = snapshot.val();
console.log("IN"+username)
}
});
console.log("OUT"+username)
return username
}
问题是在 if() 之外,用户名是未定义的。我读到使用 firebase 你必须异步工作,所以我遵循了这个指南:How do I return a snapshot.val() from Firebase to a variable? 所以我创建了函数:
getListings(id) {
return firebase.database().ref().child("users/"+id+"/username").once("value");
}
loadListing(id){
this.getListings(id).then(this. setListing, this.showError);
}
setListing(snapshot){
this.currentSnapshot = snapshot.val()
}
showError(e){
console.log(e);
}
init(id){
this.loadListing(id);
}
在其他页面我调用init:
export class ProfilePage implements OnInit {
username : any;
constructor(private route: ActivatedRoute, private router: Router, public authService: AuthenticationService) {};
ngOnInit() {
this.authService.init(this.authService.userData.uid)
console.log(this.authService.currentSnapshot)
}
}
但我收到错误:
错误:未捕获(承诺中):TypeError:无法设置未定义的属性“currentSnapshot”
谁能帮帮我?
【问题讨论】:
标签: typescript firebase-realtime-database promise