import { environment } from './../../environments/environment'; import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpErrorResponse, } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { AuthService } from './services/auth.service'; import { Router } from '@angular/router'; // Importer le Router pour la redirection @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor( private authService: AuthService, private router: Router // Injection du Router ) {} intercept( request: HttpRequest, next: HttpHandler ): Observable> { if (request.url.startsWith(environment.apiBaseUrl + '/api')) { const token = this.authService.getToken(); if (token) { request = request.clone({ setHeaders: { Authorization: `Bearer ${token}`, }, }); } } return next.handle(request).pipe( catchError((error: HttpErrorResponse) => { if (error.status === 401) { // Déconnexion de l'utilisateur en cas d'erreur d'authentification this.authService.logout(); // Redirection vers la page de connexion this.router.navigate(['/auth']); // Modifier '/login' selon votre chemin de la page de connexion // Vous pouvez également afficher un message d'erreur à l'utilisateur // en utilisant un service de notification ou en modifiant votre modèle pour afficher un message d'erreur } return throwError(error); }) ); } }