Angular 2,Firebase - > SignInWithRedirect()

时间:2017-07-27 16:37:38

标签: angular firebase firebase-authentication google-authentication

Firebase 使用 SignInWithRedirect()功能,登录但.user变量返回null ,也无法登录主页。相反,它总是重定向并且循环回到相同的登录页面。我怎样才能做到这一点?

Google登录打字稿代码如下所示。

googleLogin(){

var provider = new firebase.auth.GoogleAuthProvider();  
var profile = firebase.auth().currentUser; 

provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
provider.addScope('https://www.googleapis.com/auth/userinfo.email'); 

  if (!profile) {   
    this.afauth.auth.signInWithRedirect(provider);

    firebase.auth().getRedirectResult().then((gsignres) => {

        if(gsignres.user != null){
          alert('redirect success!');
          this.navCtrl.setRoot(HomePage);
        } else{
          alert('Sign in Failed!');
        }


      }).catch((err) => {
        alert(err);
      });  

  } else {
    alert('else part of if');
    this.navCtrl.setRoot(HomePage);
    alert('root set!!!!');
  }
}

1 个答案:

答案 0 :(得分:2)

你有一个无限循环。您拨打signInWithRedirect,然后连续拨打getRedirectResult。每次回到页面时,您都会尝试登录。

您需要做的是首先通过以下方式确定用户状态: firebase.auth().onAuthStateChanged((user) => { if (user) { // Already signed in. } else { // not signed in. } })

如果没有用户,请显示一个登录按钮,点击该按钮,然后拨打signInWithRedirect。 如果有用户,如果您想从登录中获取凭据,可以致电getRedirectResult()。虽然只有用户刚刚登录才能使用,否则为空。