• Skip to main content
  • Skip to primary sidebar

Web Development Archive

  • Archive
You are here: Home / Angular / Auth Service Example with FireBase

Auth Service Example with FireBase

import { inject, Injectable, signal } from '@angular/core';
import {
Auth,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
signOut,
UserCredential,
onAuthStateChanged,
User,
} from '@angular/fire/auth';
import { from, Observable } from 'rxjs';
import { Router } from '@angular/router';

@Injectable({
providedIn: 'root',
})
export class AuthService {
private readonly auth = inject(Auth);
private readonly router = inject(Router);

user = signal<User | null>(null);
isLoggedIn: boolean = false;

constructor() {
onAuthStateChanged(this.auth, (user) => {
this.user.set(user);
this.isLoggedIn = !!user;
if (user) {
console.log('Logged in as: ', user.email);
} else {
console.log('No user is logged in.');
this.router.navigate(['/login']);
}
});
}

getIsLoggedIn(): Promise<boolean> {
return new Promise((resolve) => {
onAuthStateChanged(this.auth, (user) => {
resolve(!!user);
});
});
}

signIn(email: string, password: string): Observable<UserCredential> {
return from(signInWithEmailAndPassword(this.auth, email, password));
}

signUp(email: string, password: string): Observable<UserCredential> {
return from(createUserWithEmailAndPassword(this.auth, email, password));
}

logOut() {
return signOut(this.auth);
}
}

Filed Under: Angular

About Gabor Flamich

I'm a web developer and designer based in Budapest, Hungary. In recent years, I've documented hundreds of solutions I came across during development. This site is an archive for useful code snippets on WordPress, Genesis Framework and WooCommerce. If You have any questions related to WordPress development, get in touch!

Primary Sidebar

  • angular.io
© 2026 WP Flames - All Right Reserved