简体   繁体   English

JS,firebase.auth() 在全局上下文中不起作用,但在函数内部起作用? - firebase.Auth 不是函数

[英]JS, firebase.auth() doesn't work in global context but works inside the functions? - firebase.Auth is not a function

I have imported all the firebase scripts I need at the bottom of my HTML我已经在 HTML 底部导入了我需要的所有 firebase 脚本

<body>
 ...
  <script src="/__/firebase/8.0.1/firebase-app.js"></script>

  <script defer src="/__/firebase/8.0.1/firebase-auth.js"></script>
  <script defer src="/__/firebase/8.0.1/firebase-firestore.js"></script>
  <script defer src="/__/firebase/8.0.1/firebase-functions.js"></script>

  <script defer src="/__/firebase/init.js?useEmulator=true"></script>

  <script src="./scripts/app.js"></script>
</body>

and inside my app.js I'm useing firebase.auth() on form submit and it works fine.在我的 app.js 中,我在表单提交上使用firebase.auth()并且它工作正常。

loginForm.addEventListener('submit', (e) => {
  e.preventDefault();
  const email = loginForm.email.value;
  const password = loginForm.password.value;

  firebase
    .auth()  -> works fine here!
    .signInWithEmailAndPassword(email, password)
    .then((user) => {
      console.log('signed in', user);
      loginForm.reset();
    })
    .catch((error) => {
      loginForm.querySelector('.error').textContent = error.message;
    });
});

But the problem occurs when i try to write onAuthStateChanged in global context of app.js但是当我尝试在 app.js 的全局上下文中编写 onAuthStateChanged 时出现问题

  firebase.auth().onAuthStateChanged((user) => {
    ....
  });

 // throws an error "Uncaught TypeError: firebase.Auth is not a function"

funny thing is that when I console.log(firebase) it logs out correctly and I can see auth as well other methods like functions.有趣的是,当我console.log(firebase)它正确注销时,我可以看到 auth 以及其他方法,如函数。 By the way this applies to other firebase methods and not only auth .顺便说一下,这适用于其他 firebase 方法,而不仅仅是auth

Is this some kind of bug ?这是某种错误吗?

This happened to me as well.这也发生在我身上。 This is not specific to firebase and turns out you cannot call any function directly in a global context.这不是特定于 firebase 的,事实证明您不能直接在全局上下文中调用任何函数。 I suggest you place it in the componentDidMount function.我建议你把它放在 componentDidMount 函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM