[英]Angular Firebase auth, how to check if user is logged in to hide login link from navigation?
我实现了 angular firebase 电子邮件和密码注册和登录,但现在我想做的是在我的导航模板中检查用户的状态,如果用户已登录,则隐藏登录按钮,以及隐藏注册按钮。 我尝试在谷歌上搜索一些相关教程,发现我必须使用 AuthService 和 AuthInfo,如您在此处所见:
问题是他们使用了很多我不熟悉的承诺和东西,这让我很困惑。 我正在尝试以最基本的方式实现这一目标,并寻找可以指导我并帮助我的人。
现在这是我的代码:
导航 -
<ul class="nav navbar-nav">
<li><a routerLink="" routerLinkActive="active">Home</a></li>
<li><a routerLink="login" routerLinkActive="active" *ngIf="!authInfo?.isLoggedIn()">Login</a></li>
<li><a routerLink="register" routerLinkActive="active" *ngIf="!authInfo?.isLoggedIn()">Register</a></li>
<li><a routerLink="quiz" routerLinkActive="active">Quiz</a></li>
</ul>
我的Auth 服务文件包含所有用户创建并登录到 firebase 逻辑 -
@Injectable({
providedIn: 'root'
})
export class AuthService {
private user: Observable<firebase.User>;
constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
this.user = _firebaseAuth.authState;
this.user.subscribe(
(user) => {
if (user) {
this.userDetails = user;
console.log(this.userDetails);
} else {
this.userDetails = null;
}
}
);
}
logUserIn(email, pass) {
firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log("error" + error);
})
if (this.userDetails) {
email = this.userDetails.email;
console.log("hello im user" + " " + email);
} else {
console.log("not working");
}
this.router.navigate(['']);
}
regUser(email, pass) {
firebase.auth().createUserWithEmailAndPassword(email, pass)
.catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
});
}
}
登录组件 -
@Component({
selector: 'login',
templateUrl: 'login.component.html'
})
export class LoginComponent {
form: FormGroup;
constructor(fb: FormBuilder, private _loginService: LoginService, private auth: AuthService) {
this.form = fb.group({
email: ['', Validators.required],
password: ['', Validators.compose([Validators.required,
PasswordValidator.cannotContainSpace])]
})
}
login() {
this.auth.logUserIn(this.form.value.email, this.form.value.password);
};
}
来自上面 github 链接的auth-info.ts文件 -
export class AuthInfo {
constructor(public $uid: string) { }
isLoggedIn() {
return !!this.$uid;
}
}
编辑:
因此,感谢 Tushar Walzade,我设法显示和隐藏了这些按钮,但我的行为非常奇怪。 注销时没有问题,但是当我登录时,没有任何反应,我收到来自 Auth 服务中的logUserIn
方法的not working
的消息到 Chrome 控制台。 但是,当我刷新一次页面时,它会告诉我它正在工作,我在控制台中获取用户信息详细信息并且按钮被隐藏。 我不知道为什么会这样,但我认为这可能与我一无所知的sessionStorage
有关。
这是代码:
授权服务
export class AuthService {
private user: Observable<firebase.User>;
private userDetails: firebase.User = null;
public loggedIn = false;
constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
this.user = _firebaseAuth.authState;
this.loggedIn = !!sessionStorage.getItem('user');
this.user.subscribe(
(user) => {
if (user) {
this.userDetails = user;
console.log(this.userDetails);
} else {
this.userDetails = null;
}
}
);
}
// Set current user in your session after a successful login
setCurrentUser(email: string): void {
sessionStorage.setItem('user', email);
this.loggedIn = true;
}
// Get currently logged in user from session
getCurrentUser(): string | any {
return sessionStorage.getItem('user') || undefined;
}
isLoggedIn() {
return this.loggedIn;
}
logUserIn(email, pass) {
firebase.auth().signInWithEmailAndPassword(email, pass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log("error" + error);
})
//var user = firebase.auth().currentUser;
//var email;
if (this.userDetails) {
email = this.userDetails.email;
console.log("hello im user" + " " + email);
//email = user.email;
this.setCurrentUser(email);
this.loggedIn = true;
} else {
console.log("not working");
}
this.router.navigate(['']);
}
regUser(email, pass) {
firebase.auth().createUserWithEmailAndPassword(email, pass)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
//console.log(this.form.controls['email'].value);
}
logOut() {
this.loggedIn = false;
firebase.auth().signOut().then(function() {
// Sign-out successful.
console.log("signout successful");
}).catch(function(error) {
// An error happened.
console.log("error happened");
});
}
}
登录组件
导出类 LoginComponent {
form: FormGroup;
constructor(fb: FormBuilder, private _loginService: LoginService, private auth: AuthService){
this.form = fb.group({
email:['',Validators.required ],
password:['',Validators.compose([Validators.required,
PasswordValidator.cannotContainSpace])] })
}
login(){
this.auth.logUserIn(this.form.value.email, this.form.value.password);
};
}
app.component.ts因为我在app.component.html中有我的路由器插座和链接
export class AppComponent {
title = 'angular-draganddrop';
constructor(private auth: AuthService) { }
LoggedIn() {
return this.auth.isLoggedIn();
}
logout() {
return this.auth.logOut();
}
}
编辑编辑:
所以我检查了 Chrome 中的应用程序会话存储,当我注销时,我确实看到我的用户电子邮件仍然存在。 我必须手动删除它。 然后,当第一次尝试登录时,它不起作用,会话存储中也没有用户电子邮件。 第二次添加。 在将 sessionStorage 功能添加到代码之前,登录系统工作正常,因此它肯定与它相关。 我不知道 sessionStorage 是如何工作的,所以我正在寻找帮助来解决这个问题。
您需要使用会话,以便您可以在考虑页面刷新的情况下对其进行检查。
只需在您的服务AuthService
中设置和使用loggedIn
的属性,如下所示 -
public loggedIn = false;
constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
this.loggedIn = !!sessionStorage.getItem('user');
}
// Set current user in your session after a successful login
setCurrentUser(email: String): void {
sessionStorage.setItem('user', email);
this.loggedIn = true;
}
// Get currently logged in user from session
getCurrentUser(): string | any {
return sessionStorage.getItem('user') || undefined;
}
// Clear the session for current user & log the user out
logout() {
sessionStorage.removeItem('user');
this.loggedIn = false;
// ... other code for logout
}
// The method to check whether user is logged in or not
isLoggedIn() {
return this.loggedIn;
}
因此,您更新的logUserIn
方法将是 -
logUserIn(email, pass) {
firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log("error" + error);
})
if (this.userDetails) {
email = this.userDetails.email;
console.log("hello im user" + " " + email);
// setting user in session here --->
this.setCurrentUser(email);
} else {
console.log("not working");
}
this.router.navigate(['']);
}
在注销时,只需调用logout()
,如上所示。
然后只需将它添加到您的HTML中,如下所示 -
<li><a routerLink="login" routerLinkActive="active" *ngIf="!auth.isLoggedIn()">Login</a></li>
有一种更简单的方法可以做到这一点。 请在此处查看官方 github 文章: https ://github.com/angular/angularfire/blob/master/docs/auth/getting-started.md
您需要做的就是...
我的页面.component.ts
import { AngularFireAuth } from '@angular/fire/auth';
//...
constructor(public afAuth: AngularFireAuth) { }
我的页面.component.html
<div *ngIf="(afAuth.user | async)">User is logged IN</div>
<div *ngIf="!(afAuth.user | async)">User is logged OUT</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.