[英]Firebase logout generates a login page
我有這個Angular 6項目,嘗試在其中使用Firebase添加登錄/注銷功能。 這是我的代碼:
isLoggedIn = false;
constructor(private afAuth: AngularFireAuth) {
this.uid = this.afAuth.authState.pipe(
map(authState => {
if (!authState) {
return null;
} else {
this.isLoggedIn = true;
return authState.uid;
}
}),
);
}
login() {
try {
this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider()).then(() => {
this.isLoggedIn = true;
console.log(1234, this.isLoggedIn);
});
} catch (e) {
console.log(e.message);
}
}
logout() {
try {
this.afAuth.auth.signOut().then(() => {
this.isLoggedIn = false;
console.log(4321, this.isLoggedIn);
});
} catch (e) {
console.log(e.message);
}
}
<button *ngIf="isLoggedIn" class="btn btn-danger" type="button" (click)="logout()">Log Out</button>
<button *ngIf="!isLoggedIn" class="btn btn-danger" type="button" (click)="login()">Log In</button>
我的問題是,當我按下“注銷”按鈕時,由於顯示了登錄按鈕,似乎注銷了用戶,但隨后彈出了一個新的登錄窗口。 我究竟做錯了什么。 如果您有任何疑問,請隨時發表評論,因為我反應迅速。
(這是整個工作代碼嗎?)除了用戶情況是發生雙擊(注銷然后立即登錄)之外,我沒有看到任何應重新觸發登錄的內容。
無需在登錄/注銷方法中手動設置“ isLoggedIn”,您就可以為此訂閱保持authState(構造函數中的subscription已經完成了大部分工作,應該是ngOnInit)。 使用authState驅動這是一個好主意,因為如果登錄或注銷失敗,則isLoggedIn變量將不會與實際的authState不同步。
ngOnInit() {
this.afAuth.authState.pipe(
tap((user: User | null) =>
this.isLoggedIn = user !== null
),
).subscribe();
// either store the subscription and unsubscribe in destroy,
// or implement something like takeUntil and the subject to cancel on destroy
}
如果您覺得UI更改速度過快,則可以添加加載狀態(可能會強制延遲),這樣就可以清楚UI的功能。 下面的示例使用用戶操作來設置加載狀態(等待某些事情發生),對auth狀態的訂閱將更新“ isLoggedIn”,然后強制延遲,然后再將加載狀態設置為false。
loadingSubject = new BehaviorSubject<boolean>(false);
loading$ = this.loadingSubject.asObservable();
isLoggedIn = false;
constructor(private afAuth: AngularFireAuth) {}
ngOnInit() {
this.afAuth.authState.pipe(
tap((user: User | null) =>
this.isLoggedIn = user !== null
),
delay(300),
tap(() =>
this.loadingSubject.next(false)
),
).subscribe();
// either store the subscription and unsubscribe in destroy,
// or implement something like takeUntil and the subject to cancel on destroy
}
login() {
this.loadingSubject.next(true);
this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider());
}
logout() {
this.loadingSubject.next(true);
this.afAuth.auth.signOut();
}
<mat-progress-spinner *ngIf="loading$ | async; else buttons" [mode]="'indeterminate'"></mat-progress-spinner>
<ng-template #buttons>
<button *ngIf="isLoggedIn" class="btn btn-danger" type="button" (click)="logout()">Log Out</button>
<button *ngIf="!isLoggedIn" class="btn btn-danger" type="button" (click)="login()">Log In</button>
</ng-template>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.