Question presented to candidate:
"Every request from our Angular app needs an auth header, and we want to log how long each API call takes, without touching the forty services that call HttpClient. What is an HTTP interceptor and how would you use one here?"
What a strong answer should cover:
- An interceptor is middleware in
HttpClient's pipeline: it sees every outgoingHttpRequestand every incomingHttpEvent, and can change, replace or short-circuit either. - Modern form: an
HttpInterceptorFn(req, next) => next(req), registered withprovideHttpClient(withInterceptors([...])); it runs in an injection context, soinject()works. - Requests are immutable: change them with
req.clone({ setHeaders: ... }). - Order: requests flow through interceptors in array order, responses come back in reverse order; an interceptor that does not call
nextends the chain (fake backends, caches). - Legacy class interceptors (
HttpInterceptor+HTTP_INTERCEPTORS) needwithInterceptorsFromDi(); both kinds can coexist, ordered by where the features are listed. - Only requests made with
HttpClientare intercepted.
Clarifying questions expected:
- "Should the token go to every URL, or only our own API?"
- "Is anything else already registered as an interceptor, such as a library's?"
Code / implementation expected: Yes β an auth interceptor, a timing interceptor and a fake backend, with a log of the order they run in.