How do you create an Interceptor? It is a service or class?

We can create by implementing the HttpInterceptor interface from @angular/common/http package. We register it to be attached to the HTTP request pipeline by adding it to the providers array in the NgModule. We can also enable DI into the interceptor by registering it as a service.

@Injectable({
    providedIn: "root"
})
export class PostsInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler)
      : Observable<HttpEvent<any>> {
        // fiddling happens here
        return next.handle(req);
    }
}
// NgModule
providers: [{
       provide: HTTP_INTERCEPTORS,
       useClass: PostsInterceptor,
       multi: true
}]

We can create by implementing the HttpInterceptor interface from @angular/common/http package. We register it to be attached to the HTTP request pipeline by adding it to the providers array in the NgModule. We can also enable DI into the interceptor by registering it as a service.

@Injectable({
    providedIn: "root"
})
export class PostsInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler)
      : Observable<HttpEvent<any>> {
        // fiddling happens here
        return next.handle(req);
    }
}
// NgModule
providers: [{
       provide: HTTP_INTERCEPTORS,
       useClass: PostsInterceptor,
       multi: true
}]
Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.