我正在尝试将变量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();
}
答案 0 :(得分:0)
如果我没有记错,firebase.auth().onAuthStateChanged
会返回一个承诺,所以我认为你需要then()
之后
firebase.auth().onAuthStateChanged(user => {
if (user) {
ownerID = user.uid;
}
}).then(data => {
console.log(ownerID)
});
返回包含void
的非null firebase.Promise