Angular provideAppInitializer to fetch csrf token cookie

Discussão em 'Angular' iniciado por user25752829, Janeiro 14, 2025.

  1. user25752829

    user25752829 Guest

    I have an app with an angular frontend and a django backend.

    I make an api call to the backend to set the csrftoken cookie so that I can send it with any POST requests to the same backend; I had originally put the api call in my app.component's (my root component's) ngOnInit method, but it led me to a problem: the cookie would not be set until I refreshed the page, presumably because the app initialization (and thus the cookie setting) would be done before the api call to get the csrf token cookie would resolve

    So I decided to start using the app initializer, but I still have the problem where the csrf token cookie is not set until I refresh the page. What am I doing wrong?

    Angular 19 deprecated APP_INITIALIZER in favor of provideAppInitializer and the official documentation is pretty scarce on this topic

    This is my providers array in app.config.ts:

    providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideHttpClient(),
    provideAppInitializer(()=>{
    inject(CsrfService).fetch_token()
    })
    ]


    While this is the service that fetches the token:

    export class CsrfService {
    constructor(private http:HttpClient) { }

    token: string;

    fetch_token(){
    return new Promise(()=>{
    this.http.get<{ token: string }>('localhost/fake/url', { withCredentials: true })
    .subscribe({
    next: (response) => {
    this.token = response.token;
    },
    error: (error) => console.error('Error fetching CSRF token', error),
    });
    });
    }
    }

    Continue reading...

Compartilhe esta Página