我试图在firebase函数之外传递变量 ownerID
,但是即使函数在函数之外声明了变量,它也会在关闭函数后未定义。我该如何解决?
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();
}
如果我没记错的 firebase.auth().onAuthStateChanged
返回诺言,所以我认为您需要一个 then()
firebase.auth().onAuthStateChanged(user => {
if (user) {
ownerID = user.uid;
}
}).then(data => {
console.log(ownerID)
});
onauthstatatechanged
返回非壁炉式firebase.promise包含void