[英]Firebase: Keep user logged in angular 7
I use firebase and angularfire2 within an authentication system! 我在身份验证系统中使用firebase和angularfire2!
The problem is that after refresh the user needs to log in again! 问题是刷新后,用户需要再次登录! I need to avoid that issue so I found out that firebase gives me that option by using
authState
我需要避免该问题,所以我发现
authState
通过使用authState
给了我该选项
but still not working! 但仍然无法正常工作!
This the code for the authService: 这是authService的代码:
import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/internal/observable';
import { NavController } from '@ionic/angular';
import { ToastMessagesService } from './toast-messages.service';
import * as firebase from 'firebase';
@Injectable({
providedIn: 'root'
})
export class AuthService {
public user: Observable<firebase.User>;
public userDetails: firebase.User = null;
constructor(
private af: AngularFireAuth,
private navCtrl: NavController,
private statusMessage: ToastMessagesService
) {
this.user = af.authState;
this.user.subscribe(
user => this.userDetails = user
)
}
async siginInRegular(username: string, password: string) {
try {
// const credentials = this.af.auth.email
return await this.af.auth.signInWithEmailAndPassword(username, password).then(
user => {
if (user) {
this.navCtrl.navigateForward('/home');
this.statusMessage.message(`Welcome ${user.user.email}`);
}
},
err => {
console.log(err);
}
);
} catch (error) {
console.dir(error);
}
}
async register(username: string, password: string) {
try {
return await this.af.auth.createUserWithEmailAndPassword(username, password).then(
user => {
this.navCtrl.navigateForward('/profile');
this.statusMessage.message(`Welcome ${user.user.email}`);
}
);
} catch (error) {
console.dir(error);
}
}
signOut() {
return this.af.auth.signOut();
}
isLoggedIn(): boolean {
return (this.userDetails != null) ? true : false;
}
}
The guard code: 防护码:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
import { NavController } from '@ionic/angular';
import { AngularFireAuth } from 'angularfire2/auth';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(
private auth: AuthService,
private navCtrl: NavController,
private af: AngularFireAuth
) {
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (this.auth.isLoggedIn()) {
return true
}
console.log('Access denied!');
return false;
}
}
Firebase actually automatically will sign the user in when you reload the page. 当您重新加载页面时,Firebase实际上会自动使用户登录。 But since your handling of the sign-in is only in the
then()
block, it only happens when you explicitly sign them in. 但是由于您仅在
then()
块中处理登录,因此只有在您明确登录后才发生。
To fix this, you want to use an onAuthState
listener as shown in get the currently signed in user : 要解决此问题,您想要使用
onAuthState
侦听器,如获取当前登录的用户所示 :
firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. } else { // No user is signed in. } });
Unlike the then()
handler, this onAuthStateChanged
handler will be called every time the user's authentication state changes, including when you reload the page. 与
then()
处理程序不同,此onAuthStateChanged
处理程序将在每次用户的身份验证状态更改时被调用,包括在您重新加载页面时。
Since you're using AngularFire2, you can also use af.auth.subscribe
as shown here: How to get the firebase.User in AngularFire2 由于您使用的是AngularFire2,因此您还可以使用
af.auth.subscribe
,如下所示: 如何获取firebase.AngularFire2中的用户
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.