Refreshing CSRF Tokens after Each Request in Angular

Provide a code snippet for an Angular service that refreshes the CSRF token after each successful HTTP request.
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { tap } from 'rxjs/operators';

  providedIn: 'root'
export class CsrfService {
  private csrfToken: string | null = null;

  constructor(private http: HttpClient) {}

  // Call this method to refresh CSRF token
  public refreshCsrfToken(): void {
    this.http.get('/api/csrf-token') // Replace with your endpoint
        tap((response: any) => {
          // Handle the response and set the csrfToken with the new value
          this.csrfToken = response.csrfToken;
          // Update default headers with the new CSRF token
          this.http.options = {
            headers: new HttpHeaders({
              'X-CSRF-TOKEN': this.csrfToken

  // Use this method to make HTTP request with updated CSRF token
  public makeRequest(): void {
    // Example request
        tap(() => this.refreshCsrfToken()) // Refresh CSRF token after each successful request
This Angular service contains a method to refresh the CSRF token after each successful HTTP request. 'refreshCsrfToken' fetches the new token and updates the HttpClient headers, while 'makeRequest' is an example of how to use the service to make a request and then refresh the token.