Firebase和ionic 2,将用户UID添加到数据库时出现问题

时间:2017-03-09 18:00:36

标签: typescript firebase firebase-realtime-database ionic2 firebase-authentication

我正在尝试将变量ownerID传递给Firebase函数之外,但是在函数关闭后它会变为UNDEFINED,即使变量是在函数外部声明的。我该如何解决这个问题?

addBook():void {
var ownerID
let prompt = this.alertCtrl.create({
  title: 'Adicionar Livros',
  message: 'Adicione as informações do livro',
  inputs: [
    {
      name: 'title',
      placeholder: "Título do Livro"
    },
    {
      name: 'author',
      placeholder: "Nome do Autor"
    },
    {
      name: 'description',
      placeholder: "Descrição do Livro"
    },
    {
      name: 'city',
      placeholder: "Sua Cidade"
    },
  ],
  buttons: [
    {
      text: "Cancelar",
      handler: data => {
        console.log("cancel clicked");
      }
    },
    {
      text: "Salvar",
      handler: data => {
        firebase.auth().onAuthStateChanged(function(user) {
          if (user) {
            ownerID = user.uid;
            console.log(ownerID); // this prints fine
          }
        })
          console.log(ownerID) // this is undefined
        this.books.push({
          title: data.title,
          author: data.author,
          description: data.description,
          city: data.city,
          owner: ownerID
        })
      }
    }
  ],
})
prompt.present();
}

1 个答案:

答案 0 :(得分:0)

如果我没有记错,firebase.auth().onAuthStateChanged会返回一个承诺,所以我认为你需要then()之后

firebase.auth().onAuthStateChanged(user => {
   if (user) {
      ownerID = user.uid;
   }
}).then(data => {
   console.log(ownerID)
});

onAuthStateChanged

  

返回包含void

的非null firebase.Promise