簡體   English   中英

為什么firebase.auth().currentUser即使用戶登錄也返回NULL

[英]Why does firebase.auth().currentUser return NULL even when the user is logged in

我正在使用 Firebase 登錄我的應用程序,如下所示 -

onSubmit(form){
this.authService.login(form.value.usermail, form.value.userpswd)
.then((data) => {
 this.router.navigateByUrl('/dashboard');

}).catch((error) => {
  this.errorMessage = error;
})

authService is -  login(email: string, password: string) {
                  return firebase.auth().signInWithEmailAndPassword(email, password)
                  }

我想檢查用戶是否登錄或退出,並在此基礎上相應地在我的導航欄上設置項目/標簽。 例如,只有當用戶已經登錄時,用戶才會在導航欄中看到 LOGOUT label 等。

HTML -

  <li class="nav-item" data-target=".navbar-collapse" data-toggle="collapse" 
   routerlinkactive="active"
   *ngIf="loggedIn">
    <a class="nav-link" (click)="logOut()">LOGOUT</a>
  </li>

我的導航組件上的代碼是-

import { Component, OnInit } from '@angular/core';
import * as firebase from 'firebase/app';
import 'firebase/auth';
import { Router } from '@angular/router';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {

loggedIn : boolean = false;
user : any

constructor(private router: Router) {

this.user = firebase.auth().currentUser;

if(this.user){
  this.loggedIn = true;

} else {
  this.loggedIn = false;

}


firebase.auth().onAuthStateChanged((user)=>{
if(this.user){
  this.loggedIn = true;

} else {
  this.loggedIn = false;

}
console.log(firebase.auth().currentUser) 
console.log(firebase.auth()) 

}

ngOnInit() {
}

logOut(){

 console.log("LOGOUT")
 firebase.auth().signOut();
 this.router.navigateByUrl("/signup");

}
}

即使 firebase.auth() 給出了正確的數據,firebase.auth().currentUser 返回 NULL 因為我無法設置登錄變量的值。

我發現了許多類似的問題,但到目前為止沒有任何解決方案。 任何幫助將不勝感激!

提前致謝 !!

避免使用 firebase.auth().currentUser 檢查 state,而是將邏輯放在觀察者中。

export class MenuComponent implements OnInit {

    loggedIn: boolean = false;

    constructor(private router: Router) {

        firebase.auth().onAuthStateChanged((user) => {
            if (user) {
                this.loggedIn = true;

            } else {
                this.loggedIn = false;
            }
        } 

        console.log("LOGOUT")
        firebase.auth().signOut();
        this.router.navigateByUrl("/signup");

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM