npm install @angular/fire firebase --save
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private afAuth: AngularFireAuth) { }
async login(email: string, password: string) {
try {
const result = await this.afAuth.signInWithEmailAndPassword(email, password);
return result;
} catch (error) {
console.log(error);
}
}
async register(email: string, password: string) {
try {
const result = await this.afAuth.createUserWithEmailAndPassword(email, password);
return result;
} catch (error) {
console.log(error);
}
}
async logout() {
try {
await this.afAuth.signOut();
} catch (error) {
console.log(error);
}
}
}
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
async canActivate(): Promise {
const user = await this.authService.getCurrentUser();
if (user) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomePage } from './home.page';
import { AuthGuard } from '../services/auth.guard';
const routes: Routes = [
{
path: '',
component: HomePage,
canActivate: [AuthGuard]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class HomePageRoutingModule {}
上一篇:AuthenticatingSveltekitwithJWTAPIusingcookies
下一篇:Authentication+PersistantloginwithJWTandrefreshtoken(使用JWT和刷新令牌进行身份验证和持久登录)