Complete the code to create an HTTP interceptor class in Angular.
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http'; @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler) { const clonedReq = req.clone({ headers: req.headers.set('[1]', 'Bearer token') }); return next.handle(clonedReq); } }
The interceptor adds an Authorization header to the HTTP request to modify it before sending.
Complete the code to register the interceptor in the Angular provider array.
import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { AuthInterceptor } from './auth.interceptor'; providers: [ { provide: HTTP_INTERCEPTORS, useClass: [1], multi: true } ]
You register the interceptor class AuthInterceptor to the HTTP_INTERCEPTORS token to enable it.
Fix the error in the interceptor method to correctly handle the request and response.
intercept(req: HttpRequest<any>, next: HttpHandler) {
const modifiedReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer token') });
return next.[1](modifiedReq);
}The handle method of HttpHandler forwards the modified request to the next interceptor or backend.
Fill both blanks to create an interceptor that adds a custom header only if the request URL contains 'api'.
intercept(req: HttpRequest<any>, next: HttpHandler) {
if (req.url.[1]('api')) {
const cloned = req.clone({ headers: req.headers.set('[2]', 'CustomValue') });
return next.handle(cloned);
}
return next.handle(req);
}The includes method checks if 'api' is in the URL. The header added is 'Authorization' with a custom value.
Fill all three blanks to create an interceptor that logs the request method, URL, and then forwards the request.
intercept(req: HttpRequest<any>, next: HttpHandler) {
console.log('Request Method:', req.[1]);
console.log('Request URL:', req.[2]);
return next.[3](req);
}The interceptor logs the method and url properties of the request, then calls handle to continue.