【问题标题】:Firebase and ionic 2, issue when adding user UID to databaseFirebase 和 ionic 2,将用户 UID 添加到数据库时出现问题
【发布时间】:2017-07-30 20:27:09
【问题描述】:

我正在尝试将变量 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();
}

【问题讨论】:

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


    【解决方案1】:

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

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

    onAuthStateChanged

    返回包含 void 的非 null firebase.Promise

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 2017-10-06
      • 1970-01-01
      • 2015-12-15
      • 2017-12-28
      • 2015-12-02
      • 2018-03-18
      • 1970-01-01
      • 2019-04-16
      相关资源
      最近更新 更多