Skip to main content

Overview

The AuthService is a core Angular service that manages user authentication state, session storage, and provides reactive streams for authentication status. It handles JWT tokens, user information, and login/logout operations.

Import

import { AuthService } from 'src/app/core/services/auth.service';
import { AuthUser } from 'src/app/shared/models/auth.model';

Properties

EventEmitters

The service uses BehaviorSubject internally to provide reactive authentication state:
userMailSubject
BehaviorSubject<string | null>
required
Internal subject that emits the current user’s email address
userLoggedInSubject
BehaviorSubject<boolean>
required
Internal subject that emits the current authentication status

Methods

setUserSession

Stores the complete user session including auth token and user information.
setUserSession(user: AuthUser, token: string): void
user
AuthUser
required
The authenticated user object containing email and name
token
string
required
The JWT authentication token returned from the server
Example:
const user: AuthUser = { _id: '123', email: '[email protected]', name: 'John Doe' };
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';

authService.setUserSession(user, token);

setAuthToken

Stores the authentication token in session storage and updates login state.
setAuthToken(token: string): void
token
string
required
The JWT token to store

getAuthToken

Retrieves the current authentication token from session storage.
getAuthToken(): string | null
return
string | null
The stored JWT token, or null if not authenticated
Example:
const token = authService.getAuthToken();
if (token) {
  // User is authenticated
  console.log('Token:', token);
}

isLoggedInObservable

Provides an Observable stream of the user’s authentication status.
isLoggedInObservable(): Observable<boolean>
return
Observable<boolean>
Observable that emits true when user is logged in, false otherwise
Example:
authService.isLoggedInObservable().subscribe(isLoggedIn => {
  if (isLoggedIn) {
    console.log('User is authenticated');
  } else {
    console.log('User is not authenticated');
  }
});

setUserMail

Stores the user’s email address in session storage.
setUserMail(userMail: string): void
userMail
string
required
The user’s email address

getUserMail

Retrieves the user’s email address from session storage.
getUserMail(): string | null
return
string | null
The user’s email address, or null if not set

getUserMailObservable

Provides an Observable stream of the user’s email address.
getUserMailObservable(): Observable<string | null>
return
Observable<string | null>
Observable that emits the current user’s email or null
Example:
authService.getUserMailObservable().subscribe(email => {
  console.log('Current user email:', email);
});

setUserName

Stores the user’s name in session storage.
setUserName(userName: string): void
userName
string
required
The user’s display name

getUserName

Retrieves the user’s name from session storage.
getUserName(): string | null
return
string | null
The user’s name, or null if not set

logOut

Clears all user session data and resets authentication state.
logOut(): void
This method:
  • Removes auth token from session storage
  • Removes user email from session storage
  • Removes user name from session storage
  • Removes user ID from session storage
  • Emits null to userMailSubject
  • Emits false to userLoggedInSubject
Example:
authService.logOut();
// User is now logged out and all session data is cleared

Storage Keys

The service uses the following session storage keys:
  • authToken - JWT authentication token
  • userMail - User’s email address
  • userName - User’s display name
  • userId - User’s unique identifier

Usage Example

import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/core/services/auth.service';
import { UserService } from 'src/app/core/services/user.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html'
})
export class LoginComponent {
  constructor(
    private authService: AuthService,
    private userService: UserService
  ) {}

  login(email: string, password: string) {
    this.userService.login({ email, password, name: '' }).subscribe({
      next: (response) => {
        // Store user session
        this.authService.setUserSession(response.user, response.token);
        
        // Check authentication status
        this.authService.isLoggedInObservable().subscribe(isLoggedIn => {
          console.log('Logged in:', isLoggedIn);
        });
      },
      error: (error) => {
        console.error('Login failed:', error);
      }
    });
  }

  logout() {
    this.authService.logOut();
  }
}

Build docs developers (and LLMs) love