1. Create the Auth Service (auth.service.ts)
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class AuthService {
private currentUserSubject: BehaviorSubject<any>;
public currentUser: Observable<any>;
constructor(private http: HttpClient) {
this.currentUserSubject = new BehaviorSubject<any>(
JSON.parse(localStorage.getItem('currentUser') || null
);
this.currentUser = this.currentUserSubject.asObservable();
}
public get currentUserValue() {
return this.currentUserSubject.value;
}
login(username: string, password: string) {
return this.http.post<any>('/api/auth/login', { username, password })
.pipe(map(user => {
// Store user details and token in local storage
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
return user;
}));
}
logout() {
// Remove user from local storage
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
getToken(): string {
const user = this.currentUserValue;
return user?.token;
}
isAuthenticated(): boolean {
return !!this.currentUserValue;
}
refreshToken() {
return this.http.post<any>('/api/auth/refresh-token', {
token: this.getToken()
}).pipe(map(user => {
this.currentUserSubject.next(user);
return user;
}));
}
}
2. Key Features
Token Storage: Uses localStorage to persist session
Observable State: Provides reactive user state via BehaviorSubject
Core Methods:
login(): Authenticates and stores session
logout(): Clears session
getToken(): Retrieves JWT
isAuthenticated(): Checks auth status
refreshToken(): Handles token renewal
3. Usage Example
// In component
constructor(private authService: AuthService) {}
login() {
this.authService.login(username, password)
.subscribe(
() => this.router.navigate(['/dashboard']),
error => this.error = error
);
}
logout() {
this.authService.logout();
this.router.navigate(['/login']);
}