我找不到有关如何使用户使用signInWithEmailAndPassword()
方法使用Firebase身份验证保持登录状态的文档或内容!
我打算使用本地存储,但是我发现Firebase提供了一个更好的选择,而不是将用户数据存储在本地存储中,但是我不知道该怎么做!
我发现具体是这样的:
firebase.auth().onAuthStateChanged();
但是我不知道如何通过我的服务和我的Guard来实现它!
这是我的身份验证服务代码:
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 {
private user: Observable<firebase.User>;
private userDetails: firebase.User = null;
constructor(
private afAuth: AngularFireAuth,
private navCtrl: NavController,
private statusMessage: ToastMessagesService
) {
this.user = afAuth.authState;
this.user.subscribe(
user => this.userDetails = user || null
)
}
async siginInRegular(username: string, password: string) {
try {
// const credentials = this.afAuth.auth.email
return await this.afAuth.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 this.afAuth.auth.createUserWithEmailAndPassword(username, password).then(
user => {
this.navCtrl.navigateForward('/profile');
this.statusMessage.message(`Welcome ${user.user.email}`);
}
);
} catch (error) {
console.dir(error);
}
}
isLoggedIn(): boolean {
return (this.userDetails != null) ? true : false
}
}
这也是我的保护代码:
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';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(
private auth: AuthService,
private navCtrl: NavController
) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (this.auth.isLoggedIn()) {
return true
}
this.navCtrl.navigateBack('/login');
return false;
}
}