javascript - firebaseAuth.onAuthStateChanged 返回用户 null
问题描述
我正在尝试使用 firebase auth 来实现身份验证,事情是当涉及到持久性时,我被卡住了。我尝试使用本地存储,如下所示:
AuthService.ts :
import {HttpClient} from '@angular/common/http';
import { Injectable } from '@angular/core';
import {AngularFireAuth} from '@angular/fire/auth';
import {Router} from '@angular/router';
import firebase from 'firebase/app';
@Injectable({
providedIn: 'root'
})
export class AuthService {
userData: any;
constructor(private http: HttpClient, private firebaseAuth: AngularFireAuth, private router: Router) {
this.firebaseAuth.useEmulator('http://localhost:9099');
this.firebaseAuth.authState.subscribe(user => {
if (user) {
this.userData = user;
localStorage.setItem('user', JSON.stringify(this.userData));
JSON.parse(localStorage.getItem('user'));
} else {
localStorage.setItem('user', null);
JSON.parse(localStorage.getItem('user'));
}
});
this.firebaseAuth.onAuthStateChanged( user => {
console.log(user);
});
}
signIn(email: string, password: string): void {
this.firebaseAuth.setPersistence(firebase.auth.Auth.Persistence.LOCAL).then(() => {
this.firebaseAuth.signInWithEmailAndPassword(email, password)
.then(result => {
this.router.navigate(['/dashboard/accueil']);
console.log('Nice, it worked!');
})
.catch(error => {
console.log('Something went wrong:', error.message);
});
}).catch(error => {
console.log('Something went wrong:', error.message);
});
}
signOut(): void {
this.firebaseAuth.signOut().then(() => {
localStorage.removeItem('user');
this.router.navigate(['/dashboard/connexion']);
});
}
forgetPassword(email: string): void {
this.firebaseAuth.sendPasswordResetEmail(email).then(() => {
window.alert('Password reset email sent, check your inbox.');
}).catch((error) => {
window.alert(error);
});
}
get isLoggedIn(): boolean {
const user = JSON.parse(localStorage.getItem('user'));
return (user !== null) ? true : false;
}
}
但问题是firebaseAuth.onAuthStateChanged在用F5甚至authState刷新页面后返回null。就像 onAuthStateChange 在刷新后失去了他的最后一个状态。
请注意,我正在使用 firebase 模拟器。
app.module.ts Firebase 模块已经很好导入
AngularFireModule.initializeApp(environment.firebase),
AngularFireAuthModule,
您可以在这里查看配置: environnement.ts
firebase: {
apiKey: 'xxxxxxxxxxxx',
projectId: 'xxxx'
}
也许这是我在刷新页面时在 Web 控制台中遇到的此错误的链接:
发布https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key=xxxxxxx 400
请注意,密钥等于我在配置中的 apiKey 状态。
当我在这里仔细观察时,错误说明了什么:
{
"error": {
"code": 400,
"message": "INVALID_ID_TOKEN",
"errors": [
{
"message": "INVALID_ID_TOKEN",
"domain": "global",
"reason": "invalid"
}
]
}
}
任何帮助将不胜感激。
编辑
从 onAuthStateChanged 刷新我的页面后,我得到了什么:
没有 2 个调用,只有 1 个返回 false。
解决方案
默认情况下,Firebase Auth 将保持登录状态,因此您不必手动将令牌保存到本地存储中。正如弗兰克所说,onAuthStateChanged 将触发用户最初为 null,但如果用户已登录,它将在不久之后以实际用户值再次触发。
推荐阅读
- javascript - 刷新值反应不是动作后的值
- c - Do-while 循环随着变量值的变化而重复
- mysql - 存储在数据库中的日期、日期格式、选择不同的日期和按顺序排序时遇到问题
- android - 如何修复尝试在空对象引用上调用虚拟方法“void android.widget.TextView.setText(java.lang.CharSequence)”
- html - 如何在 Angular 7 中从其他组件调用组件
- html - 为什么此文本未与我的 CSS 网格行垂直对齐?
- scala - 使用 json Play 处理空值
- rust - 处理标准输入上的 UTF-8 输入
- python - Matplotlib 给出 This application failed to start because it could not find or load the Qt platform plugin "xcb" in ""
- python - 当原始引用现在指向一个新值时,Python 如何知道在哪里找到创建的不可变值?