Angular9-检查Firebase用户当前是否已登录
检查用户当前是否登录到Angular 9的最佳方法是什么? 最初,我会这样做:Angular9-检查Firebase用户当前是否已登录,angular,firebase,Angular,Firebase,检查用户当前是否登录到Angular 9的最佳方法是什么? 最初,我会这样做: constructor( public afAuth: AngularFireAuth, private logger: NGXLogger ) { this.afAuth.authState.subscribe((result) => { if (result) { this.user = result; } }); }
constructor(
public afAuth: AngularFireAuth,
private logger: NGXLogger
) {
this.afAuth.authState.subscribe((result) => {
if (result) {
this.user = result;
}
});
}
public isLoggedIn(): boolean {
const user = this.afAuth.currentUser;
return !!user;
}
isLoggedIn(): boolean {
return this.authService.isLoggedIn();
}
<button
*ngIf="!isLoggedIn()"
class="btn btn-glass btn-primary"
id="builder-header-create-account"
type="button"
>
Sign Up
</button>
然后通过以下方式从我的组件调用它:
constructor(
public afAuth: AngularFireAuth,
private logger: NGXLogger
) {
this.afAuth.authState.subscribe((result) => {
if (result) {
this.user = result;
}
});
}
public isLoggedIn(): boolean {
const user = this.afAuth.currentUser;
return !!user;
}
isLoggedIn(): boolean {
return this.authService.isLoggedIn();
}
<button
*ngIf="!isLoggedIn()"
class="btn btn-glass btn-primary"
id="builder-header-create-account"
type="button"
>
Sign Up
</button>
isLoggedIn():布尔值{
返回此.authService.isLoggedIn();
}
注册
但是升级到Angular 9之后,上面的代码导致我的UI挂起。修复它的最佳方法是什么?您可以尝试使用该功能。试试下面的方法
服务
loggedIn=新行为主体(false);
loggedIn$=this.loggedIn.asObservable();
建造师(
公共授权:AngularFireAuth,
私人记录器:NGXLogger
) {
this.afAuth.auth.onAuthStateChanged((用户)=>{
如果(用户){
this.loggedIn.next(true);
}否则{
//未登录
this.loggedIn.next(false);
}
});
}
public isLoggedIn():布尔值{
return!!this.afAuth.currentUser;
}
组成部分
注册
官方的github有一小部分介绍:
你需要做的就是
myPage.component.ts
import { AngularFireAuth } from '@angular/fire/auth';
//...
constructor(public afAuth: AngularFireAuth) { }
myPage.component.html
<div *ngIf="(afAuth.user | async)">User is logged IN</div>
<div *ngIf="!(afAuth.user | async)">User is logged OUT</div>
用户已登录
用户已注销
对我有效并防止系统堵塞的是,如果我只是在观察者中进行第一个事件
this.angularFireAuth.authState.pipe(first()).subscribe(
user => {
this.isLoggedIn = !!user;
}
);
是否应该是这个.loggedIn.next(true)?除了将代码从构造函数移动到服务中的方法之外,我使用了类似的方法。然后我在app.component.ts中注入服务(这只创建了一次),并在ngOnit钩子中调用该方法。它应该是this.loggedIn.next(..)。我忽略了它。谢谢:)