使用javascript登录firebase后如何重定向到另一个页面?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用javascript登录firebase后如何重定向到另一个页面?相关的知识,希望对你有一定的参考价值。

我正在使用firebase制作一个Web应用程序。到目前为止,我已经能够创建用户并在firebase数据库中输入他们的详细信息。现在,我遇到的问题是,登录后,我希望用户被重定向到另一个页面,如下所示。我在stackoverflow上检查了类似的问题,并尝试实现它,但它无法正常工作。怎么做?

以下是代码:

   var msgRef = firebase.database().ref().child('messages');

   document.getElementById('contactform').addEventListener('submit', 
   submitLogin);

   firebase.auth().onAuthStateChanged(function(user) {
   if (user) {
     window.location = "after-login.html";
   } else {
      document.getElementById("contact").style.display = "block";
   }
  })

  function submitLogin() {
  var userEmail = document.getElementById("email").value;

  var userPass = document.getElementById("password").value;



  firebase.auth().createUserWithEmailAndPassword(userEmail, 
   userPass).catch(function(error) {
     // Handle Errors here.
     var errorCode = error.code;
     var errorMessage = error.message;
     // ...
   });
  }

我想要做的是在登录“after-login.html”后重定向我的页面。如需更多参考资料,请询问。

答案

通过javascript重定向到页面可以实现

window.location.href = yoururl;

在你的情况下你有一个catch,但问题是你没有then,这将是你的承诺的回调。因此,调用then然后在其回调中实现您需要的重定向。见这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

上面显示的源代码中的一个示例:

doSomething().then(function(result) {
  return doSomethingElse(result);
})
.then(function(newResult) {
  return doThirdThing(newResult);
})
.then(function(finalResult) {
  console.log('Got the final result: ' + finalResult);
})
.catch(failureCallback);

以上是关于使用javascript登录firebase后如何重定向到另一个页面?的主要内容,如果未能解决你的问题,请参考以下文章

如何打开 Firebase Javascript 客户端的登录?

使用 Google 登录通过 Firebase 签名后如何访问课堂 API

如何在使用 redux 登录 facebook/expo 和 firebase 后显示用户数据

谷歌登录后如何通过 Firebase 重定向到另一个屏幕? iOS

如何确保用户使用 Firebase 和 Flutter 登录

如何使用 Firebase 进行“使用 Spotify 登录”身份验证系统?