Automatically add WordPress nonce header to every Angular Http Request

Generate the wp_rest nonce and set it to be a global javascript variable that can be accessed from within angular. we have called wp_config.

// functions.php
function jc_enqueue_angular_scripts(){

    // ... Include angular scripts, this example expects your main
    // scripts file to be registered with the 'angular-main' handle. 

    $config = array(
        'site_url' => site_url('/'),
        'rest_url' => rest_url(),
        'nonce' => wp_create_nonce('wp_rest'),
    );

    wp_localize_script('angular-main', 'wp_config', $config);
}
add_action('wp_enqueue_scripts', 'jc_enqueue_angular_scripts');

Create a new HTTP_INTERCEPTOR that intercepts every http request, modifys and appends the ‘wp_rest’ nonce fetched from our global wp_config variable.

// app/http-interceptors/wp-api-interceptor.ts
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
} from '@angular/common/http';
import { Observable } from "rxjs";

export class WpApiInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const clonedRequest = req.clone({
      headers: req.headers.set('X-WP-Nonce', window['wp_config']['nonce'])
    });

    return next.handle(clonedRequest);
  }
}

Finally Include the WpApiInterceptor in your angular app/module.ts file as a provider.

// app.module.ts
import {
  HTTP_INTERCEPTORS,
  HttpClientModule
} from "@angular/common/http";

@NgModule({
    // ...
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: WpApiInterceptor,
            multi: true
        },
    ],
    
})
export class AppModule { }