Typescript : I can't get the data out of Firebase promise

烂漫一生 提交于 2019-12-24 10:38:32

问题


I am trying to pull data (the name of the user) down from firebase. I am able to pull the data down but I am not able to assign the data to anything out of firebase function. How am I supposed to get data out and use it? I want to simply update a label with the data I pull down.

getData(){
     var userID = this.firAuth.auth.currentUser.uid;
     var name;
     console.log("userID: " + userID);
     this.name = "user";
     this.firService.database.ref("/users").once('value').then(function (snapshot){
   snapshot.forEach(snap => {
     if (snap.key == userID){
       this.name = snap.val().name; //this wont work
     }
    });
  });
 }

回答1:


That's because Firebase APIs are asynchronous. That means you can't get the data out. You'll need to use it inside the function.

Alternatively, you can use async/await from ECMAScript 2017. Declare your function as async and use await to retrieve the snapshot:

async function getData(){
    var userID = this.firAuth.auth.currentUser.uid;
    var name;
    console.log("userID: " + userID);
    this.name = "user";

    var snapshot = await this.firService.database.ref("/users").once('value');
    snapshot.forEach(snap => {
        if (snap.key == userID){
            this.name = snap.val().name;
        }
    });
}


来源:https://stackoverflow.com/questions/50879562/typescript-i-cant-get-the-data-out-of-firebase-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!