【问题标题】:The user gets logged out upon reloading the page using Firebase as backend用户在使用 Firebase 作为后端重新加载页面时注销
【发布时间】:2018-01-17 07:04:59
【问题描述】:

我已经为我的 Angular 2 应用程序构建了一个身份验证。我通过使用 Firebase 身份验证服务实现了这一点。重新加载页面后,用户退出,但令牌仍然存在于 localStorage 中。

这是我的代码:

export class AdminService {

email;
password;
error;
invalidLogin;
isLoggedIn = false;

    constructor(private af: AngularFireAuth,private router: Router,private route: ActivatedRoute) {
     }


      login(){
        this.af.auth.signInWithEmailAndPassword(this.email,this.password)
        .then(authState => {
          if(authState){
            let returnUrl = this.route.snapshot.queryParamMap.get('returnUrl');
            this.router.navigate([returnUrl||'/']);
            this.isLoggedIn = true;
          }
          else this.invalidLogin = true;
        })
      }

      logout(){   

        this.af.auth.signOut();
        this.isLoggedIn = false;
        this.router.navigate(['/'])
      }

    }

【问题讨论】:

    标签: angular typescript firebase firebase-authentication angularfire2


    【解决方案1】:

    用户实际上并没有被注销。当您重新加载页面时,Firebase 客户端会检测到本地存储中的信息并再次让用户登录。您的代码只是没有检测到这一点,因此无法正确路由用户。

    在常规 Firebase JavaScript 客户端中,您可以通过 listening for the onAuthStateChanged() event 解决此问题:

    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
      } else {
        // No user is signed in.
      }
    });
    

    在 AngularFire2 中有一个FirebaseIdTokenObservable that exposes an Observable<firebase.User>。虽然我承认我从未使用过它,但这似乎也是为了做同样的事情。

    【讨论】:

      猜你喜欢
      • 2016-05-24
      • 2014-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      相关资源
      最近更新 更多