返回快照值 Firebase

时间:2021-04-07 16:26:07

标签: typescript firebase-realtime-database promise

我是 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)
  }
}

但我收到错误:

<块引用>

错误:未捕获(承诺):类型错误:无法设置未定义的属性“currentSnapshot”

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

我怀疑 mergeCells(wb = wb2, sheet = "Sheet 1", cols = 1:2, rows = 1) mergeCells(wb = wb2, sheet = "Sheet 1", cols = 1:2, rows = 2) mergeCells(wb = wb2, sheet = "Sheet 1", cols = 1:2, rows = 3) mergeCells(wb = wb2, sheet = "Sheet 1", cols = 1:2, rows = 4) mergeCells(wb = wb2, sheet = "Sheet 1", cols = 1:2, rows = 5) mergeCells(wb = wb2, sheet = "Sheet 1", cols = 1:2, rows = 6) mergeCells(wb = wb2, sheet = "Sheet 1", cols = 1:2, rows = 7) saveWorkbook(wb2, 'file.xlsx') 函数中的 this 不再引用您期望的对象。

如果这是原因,您可以通过将其绑定到正确的对象来修复它:

setListing