AI Hints
Home›Angular Tutorial›httpResource, Interceptors and Practice: A Books Client
Angular · Lesson 98 of 120

Interceptors

Code for every request.

⏱ 2 min read▶ Video at 1:58:30🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Some code should run for every request. Adding a login token, or logging, or handling errors in one place. Interceptors do that.

  • Every request
  • Tokens, logging, errors
  • Interceptors

Where interceptors sit

Every request passes through the interceptors, on its way to the server. Each one can change the request, like adding a header. The response comes back through them too, so they can see it.

  1. Component: http.get()
  2. Interceptor: change the request
  3. Server
  4. Interceptor: see the response
  5. Component gets the data

log-interceptor.ts

An interceptor is a function, with the request, and next. Requests can't be changed, so clone makes a copy, with an extra header. Next passes it on, to the server. And tap looks at the response, when it comes back.

log-interceptor.tstypescript
import { HttpInterceptorFn, HttpEventType } from '@angular/common/http';
import { tap } from 'rxjs';

export const logInterceptor: HttpInterceptorFn = (req, next) => {
  const withHeader = req.clone({ setHeaders: { 'X-Shop': 'Page Turners' } });
  const shop = withHeader.headers.get('X-Shop');
  console.log(`Sending ${req.method} ${req.url}, X-Shop: ${shop}`);
  return next(withHeader).pipe(
    tap(event => {
      if (event.type === HttpEventType.Response) {
        console.log(`Got ${event.status} for ${req.url}`);
      }
    }),
  );
};

Interceptors in action

With interceptors registers ours, in the app config. The component sends two requests, and knows nothing about the interceptor. Run it. The interceptor saw both requests, and added the header to each. Then it saw both responses come back.

app.config.tstypescript
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { logInterceptor } from './log-interceptor';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withFetch(), withInterceptors([logInterceptor])),
  ],
};
Output
Sending GET /api/books, X-Shop: Page Turners
Sending GET /api/books/2, X-Shop: Page Turners
API GET /api/books → 200
API GET /api/books/2 → 200
Got 200 for /api/books
Got 200 for /api/books/2
Also uses log-interceptor.ts
import { HttpInterceptorFn, HttpEventType } from '@angular/common/http';
import { tap } from 'rxjs';

export const logInterceptor: HttpInterceptorFn = (req, next) => {
  const withHeader = req.clone({ setHeaders: { 'X-Shop': 'Page Turners' } });
  const shop = withHeader.headers.get('X-Shop');
  console.log(`Sending ${req.method} ${req.url}, X-Shop: ${shop}`);
  return next(withHeader).pipe(
    tap(event => {
      if (event.type === HttpEventType.Response) {
        console.log(`Got ${event.status} for ${req.url}`);
      }
    }),
  );
};
Also uses app.ts
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({ selector: 'app-root', template: `<p>Two requests were sent.</p>` })
export class App {
  constructor() {
    const http = inject(HttpClient);
    http.get('/api/books').subscribe();
    http.get('/api/books/2').subscribe();
  }
}
Also uses _apilog
1

Summary

Interceptors run for every request, and can change it, or watch its response. Register them with with interceptors. Next, some practice.

Key takeaways
  • HttpInterceptorFn
  • req.clone()
  • withInterceptors([ ])
Next up: Practice: A Books Client — your turn