【问题标题】:onAuthStateChanged isn't executed after reloading the page重新加载页面后未执行 onAuthStateChanged
【发布时间】:2019-05-02 20:05:38
【问题描述】:

这是我的 firebaseApp.ts 文件:

import firebase from "firebase/app";
import "firebase/firestore";   

const config = {
  ...
};

let fb = firebase.initializeApp(config);
const database = fb.firestore();
database.settings({ timestampsInSnapshots: true });

fb.auth().onAuthStateChanged(() => {
  Vue.prototype.$isLoggedIn = firebase.auth().currentUser;
});

export const db = database;

我想从 App.vue 访问 isLoggedIn,但是当我重新加载页面并且用户登录时,不会执行 onAuthStateChanged。我必须点击某些东西才能获得“真实”价值。刷新后我应该在哪里初始化 isLoggedIn 才能正常工作?

【问题讨论】:

  • 此文件中的其他代码是否正常工作?
  • 这是我在这个文件中的所有代码。我可能做错了什么。如果我的 firebaseApp.ts 文件中有这个,我应该在哪里调用它以及如何调用它?

标签: typescript firebase vue.js


【解决方案1】:

如果您使用app.firestore();,您还应该使用app.auth()....,如下所示:

let app = firebase.initializeApp(config);
const database = app.firestore();
database.settings({ timestampsInSnapshots: true });

app.auth().onAuthStateChanged(() => {
  Vue.prototype.$isLoggedIn = firebase.auth().currentUser;
});

不确定app 是传递firebase.initializeApp(config); 的常量的最佳名称,您可以直接调用firebasefb

【讨论】:

  • 谢谢!我改变了它,但是当我重新加载页面时仍然没有执行 onAuthStateChanged...:/
  • 您是否导入 Firebase?在另一条评论中,您说这是您的所有代码,但您应该导入它。
  • 当然是导入了。我的工具栏可能有问题。我想刷新那里的按钮...我插入了代码。
【解决方案2】:

我自己解决了!我必须像这样将 onAuthStateChanged 放在我的 main.ts 中:

let app: Vue;

firebase.auth().onAuthStateChanged(function(user) {
  if (!app) {
    Vue.prototype.$isLoggedIn = firebase.auth().currentUser;
    new Vue({
      router,
      store,
      render: h => h(App)
    }).$mount("#app");
  }
});

我是 Vue 新手,非常感谢您的帮助! :)

【讨论】:

    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 2021-06-02
    相关资源
    最近更新 更多