【问题标题】:Return snapshot value Firebase返回快照值 Firebase
【发布时间】: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


    【解决方案1】:

    我怀疑您的setListing 函数中的this 不再引用您期望的对象。

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

    this.getListings(id).then(this.setListing.bind(this));
    

    【讨论】:

    • 我试过你的评论。现在我没有错误 "Error: Uncaught (in promise): TypeError: Cannot set property 'currentSnapshot' of undefined" 。但是行 console.log(this.authService.currentSnapshot) 返回“未定义”
    • 是的,这是我对整个代码的主要关注点:您没有处理数据以一致方式异步加载的事实。您需要始终如一地返回一个承诺,使用一次 then() 并不意味着其余代码可以同步访问数据库中的值。我的期望是 console.log(this.authService.currentSnapshot) 在 this.currentSnapshot = snapshot.val() 执行之前运行。在调试器中运行代码(或添加一些日志记录)确认这一点,并将其带回stackoverflow.com/q/40688268
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    相关资源
    最近更新 更多