How can I set the header in every request in angular? Let’s say I have token in localStorage and that needs to set for every REST API call.
Add AuthInterceptor that will intercept all your HTTP requests and add the token to its headers:
AuthInterceptor
import { Injectable } from '@angular/core'; import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = localStorage.token; // you probably want to store it in localStorage or something if (!token) { return next.handle(req); } const req1 = req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`), }); return next.handle(req1); } }
Then register it in your AppModule:
AppModule
@NgModule({ declarations: [...], imports: [...], providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }, ], bootstrap: [ AppComponent ], }) export class AppModule { }