How can you pass a header to all the http requests created from an angular app?

We can read an outgoing HTTP request from an angular application and modify it to always pass a particular header, such as an Authorization header carrying a token to the API by registering a HttpInterceptor. We can also make use of it to read a response before being relayed to the actual source of request. It thereby provides use cases such as Logging, Exception Handling and Headers etc.

@Injectable({
    providedIn: "root"
})
export class PostsInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler)
          : Observable<HttpEvent<any>> {
        // req object can be modified here
        return next.handle(req);
    }
}

We can read an outgoing HTTP request from an angular application and modify it to always pass a particular header, such as an Authorization header carrying a token to the API by registering a HttpInterceptor. We can also make use of it to read a response before being relayed to the actual source of request. It thereby provides use cases such as Logging, Exception Handling and Headers etc.

@Injectable({
    providedIn: "root"
})
export class PostsInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler)
          : Observable<HttpEvent<any>> {
        // req object can be modified here
        return next.handle(req);
    }
}

Buy Me A Coffee

Found this article helpful? Please consider supporting!

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.

Leave a Reply

Your email address will not be published. Required fields are marked *