[英]Why does firebase.auth().currentUser return NULL even when the user is logged in
I am logging in my application using Firebase as below -我正在使用 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)
}
I want to check if the user is logged in or out and on the basis of it set items/labels on my navigation bar accordingly.我想检查用户是否登录或退出,并在此基础上相应地在我的导航栏上设置项目/标签。 For example, the user will see LOGOUT label in the nav bar only if he is already logged in, etc.
例如,只有当用户已经登录时,用户才会在导航栏中看到 LOGOUT label 等。
HTML - 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>
The code on my navigation component is -我的导航组件上的代码是-
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");
}
}
Even though firebase.auth() gives the correct data, firebase.auth().currentUser returns NULL because of which I am not able to set the value of loggedIn variable.即使 firebase.auth() 给出了正确的数据,firebase.auth().currentUser 返回 NULL 因为我无法设置登录变量的值。
I have found many similar questions but have had no luck with any solution so far.我发现了许多类似的问题,但到目前为止没有任何解决方案。 Any help would be highly appreciated !!
任何帮助将不胜感激!
Thanks in advance !!提前致谢 !!
Avoid checking state with firebase.auth().currentUser, put the logic in the observer instead.避免使用 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.