Blog>
Snippets

Retrieving and Storing CSRF Tokens in Angular Service

Show how to create an Angular service to retrieve and store CSRF tokens that can be used across different components.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class CsrfService {
  private csrfToken: string | null = null;

  constructor(private http: HttpClient) {}

  // Method to retrieve CSRF token from the server
  retrieveCsrfToken(): void {
    this.http.get<{ csrfToken: string }>('/api/csrf-token')
      .subscribe((response) => {
        this.csrfToken = response.csrfToken;
      }, (error) => {
        console.error('Error retrieving CSRF token', error);
      });
  }

  // Method to get the stored CSRF token
  getCsrfToken(): string | null {
    return this.csrfToken;
  }
}
This Angular service 'CsrfService' provides methods to retrieve and store CSRF tokens from the server, and to access the token within other parts of the application. The 'retrieveCsrfToken' method gets the CSRF token from the server and stores it in the private 'csrfToken' variable, while the 'getCsrfToken' method returns the stored CSRF token for use.