gpt4 book ai didi

javascript - Angular 6 AngularFireAuth 检查用户是否在页面呈现之前登录

转载 作者:太空狗 更新时间:2023-10-29 18:37:55 29 4
gpt4 key购买 nike

我已经使用 Firebase 身份验证和 Cloud Fire Store 建立了一个新的 Angular 6 项目。有一个登录页面,您可以在其中通过谷歌登录,用户数据保存在 Firestore 中(代码如下)。我唯一的问题是如何检查用户是否已经登录,有什么最佳做法吗?

目前我正在异步获取用户数据,但随后导航开始闪烁。一秒钟有登录按钮,然后切换到注销按钮。在呈现页面之前是否有检查登录状态的好方法? enter image description here one second later

User.ts

export interface User {
uid: string;
email: string;
}

auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import * as firebase from 'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFirestore, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { User } from './user';

@Injectable({
providedIn: 'root'
})
export class AuthService {

user: Observable<User>;

constructor(private afAuth: AngularFireAuth, private afs: AngularFirestore, private router: Router) {
this.user = this.afAuth.authState.pipe(
switchMap(user => {
if (user) {
return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
} else {
return of(null);
}
}))
}

public googleLogin() {
const provider = new firebase.auth.GoogleAuthProvider()
return this.oAuthLogin(provider);
}

public signOut() {
this.afAuth.auth.signOut();
}

private oAuthLogin(provider) {
return this.afAuth.auth.signInWithPopup(provider)
.then((credential) => {
this.updateUserData(credential.user)
})
}

private updateUserData(user) {
const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.uid}`);
const data: User = {
uid: user.uid,
email: user.email
}
return userRef.set(data, { merge: true })
}

}

navigation.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../core/auth.service';
import { AngularFireAuth } from 'angularfire2/auth';

@Component({
selector: 'app-navigation',
templateUrl: './navigation.component.html',
styleUrls: ['./navigation.component.scss']
})
export class NavigationComponent implements OnInit {

constructor(public auth: AuthService) { }

ngOnInit() {}

auth.service.ts

<div *ngIf="auth.user | async; then loggedIn else loggedOut"></div>

<ng-template #loggedOut>
<li class="nav-item d-none d-md-inline-block pl-2 pr-0">
<a class="btn btn-sm btn-primary u-btn-primary u-btn-pill transition-3d-hover" href="/login">
Login
</a>
</li>
</ng-template>

<ng-template #loggedIn>
<li class="nav-item d-none d-md-inline-block pl-2 pr-0">
<a class="btn btn-sm btn-primary u-btn-primary u-btn-pill transition-3d-hover" (click)="auth.signOut()">
Logout
</a>
</li>
</ng-template>

最佳答案

您可能很久以前就明白了这一点,但其他人可能会疑惑。我选择检查 angularFireAuth 的 authState。如果它为空,则您已注销。然后您可以按照 Ryan Chenkie's Medium article 中的说明使用路由守卫

@Injectable()
export class FirebaseAuthService {
private authState: Observable<firebase.User>
private currentUser: firebase.User = null;

constructor(
public afAuth: AngularFireAuth,
private http: HttpClient,
private localStorage: LocalStorageService,
private router: Router,
private snackBar: MatSnackBar) {
this.authState = this.afAuth.authState;

this.authState.subscribe(user => {
if (user) {
this.currentUser = user;
this.localStorage.storeSimple('userData', user)
this.openSnackBar('Successfully authenticated');
console.log('AUTHSTATE USER', user)
this.router.navigate(['home']);
} else {
console.log('AUTHSTATE USER EMPTY', user)
this.currentUser = null;
}
},
err => {
this.openSnackBar(`${err.status} ${err.statusText} (${err.error.message})`, 'Please try again')
});
}

isAuthenticated(): boolean {
return this.authState !== null;
}

loginEmail(email, password, route) {
this.afAuth.auth.signInWithEmailAndPassword(email, password).catch(error => {
let errorCode = error.code;
let errorMessage = error.message;
this.openSnackBar(error, 'OK')
});
}

logout() {
this.afAuth.auth.signOut()
.then(response => this.openSnackBar('Signed out'))
.catch(error => this.openSnackBar('Error signing out: ' + error));
}

...
}

关于javascript - Angular 6 AngularFireAuth 检查用户是否在页面呈现之前登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50572683/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com