Understanding how to apply Angular Signals from beginning on an existing service

26 Views Asked by At

I just started to look at the documentation of Angular Signals and I am not able to make heads or tails of how to use it in the Authentication Service that I have made previously.

import { Injectable } from '@angular/core';
import {
  User,
  UserCredential,
  createUserWithEmailAndPassword,
  getAuth,
  signInWithEmailAndPassword,
} from '@angular/fire/auth';
import { LoginUser, SignUpUser } from '../models/user.model';
import { catchError, from, map, of, switchMap, tap, throwError } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { Auth, authState } from '@angular/fire/auth';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  authState$ = authState(this.angularAuth);

  constructor(
    private angularAuth: Auth,
    private router: Router,
    private toastrService: ToastrService
  ) {}

  signUp(user: SignUpUser) {
    let auth = getAuth();
    return from(
      createUserWithEmailAndPassword(auth, user.email, user.password)
    ).pipe(
      catchError((error: HttpErrorResponse) => {
        this.handleError(error);
        return of({});
      }),
      tap((userCredential: UserCredential) => {
        if (Object.keys(userCredential).length !== 0) {
          console.log(userCredential);
          this.toastrService.success(
            'Account created successfully',
            'Success',
            {
              timeOut: 5000,
            }
          );
          this.router.navigate(['login']);
        }
      })
    );
  }

  logIn(user: LoginUser) {
    let auth = getAuth();

    return from(
      signInWithEmailAndPassword(auth, user.email, user.password)
    ).pipe(
      catchError((error: HttpErrorResponse) => {
        this.handleError(error);
        return throwError(() => error);
      }),
      switchMap(() => {
        return this.authState$.pipe(
          map((user: User) => {
            if (user) {
              this.setUser(user);
              this.toastrService.success('Successfully logged in', 'Success', {
                timeOut: 2000,
              });
              this.router.navigate(['/leaderboards']);
            }
          })
        );
      })
    );
  }

  setUser(user: User) {
    localStorage.setItem('user', JSON.stringify(user!.toJSON()));
  }

  get isLoggedIn(): boolean {
    const user = localStorage.getItem('user');
    return !!user;
  }

  logout() {
    return from(this.angularAuth.signOut()).pipe(
      catchError((error: HttpErrorResponse) => {
        this.handleError(error);
        return throwError(() => error);
      }),
      tap(() => {
        localStorage.removeItem('user');
        this.toastrService.success('Successfully logged out', 'Success', {
          timeOut: 3000,
        });
        this.router.navigate(['/login']);
      })
    );
  }

  handleError(errorMsg: HttpErrorResponse) {
    let errorMessage;
    // console.log(errorMsg);
    if (errorMsg.message.includes('(auth/email-already-in-use)')) {
      errorMessage = 'Email already exists. Enter a new Email';
    } else if (errorMsg.message.includes(' (auth/invalid-credential)')) {
      errorMessage = 'Invalid Email or Password';
    } else {
      errorMessage = 'An Unknown error has occurred. Try again later';
    }

    // Alternate Method (For Reference )

    // console.log(errorMsg.message);
    // switch (errorMsg.message) {
    //   case 'Firebase: The email address is already in use by another account. (auth/email-already-in-use).':
    //     errorMessage = 'Email already exists. Enter a new Email';
    //     break;
    //   case 'Firebase: Error (auth/invalid-credential).':
    //     errorMessage = 'Invalid Email or Password';
    //     break;
    //   default:
    //     errorMessage = 'An Unknown error has occurred. Try again later';
    //     break;
    // }
    this.toastrService.error(errorMessage, 'Error', {
      timeOut: 4000,
    });
  }
}

How can I use Angular signals for anything in this service even if it is a small change. Any sort of help or hint will be appreciated

So far I have not been able to implement any changes

0

There are 0 best solutions below