I just noticed that the Header Object that was possible to use in the previous HTTP RequestsOption is not anymore supported in the new Interceptor.
It's the new Interceptor logic:
// Get the auth header from the service.
const authHeader = this.auth.getAuthorizationHeader();
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
I have, now, two ways to add my headers in this request:
Example:
headers?: HttpHeaders;
headers: req.headers.set('token1', 'asd')
setHeaders?: {
[name: string]: string | string[];
};
setHeaders: {
'token1': 'asd',
'token2': 'lol'
}
How can I add multiple headers conditionally on this request? Same to what I used to do with the Header Object:
myLovellyHeaders(headers: Headers) {
headers.set('token1', 'asd');
headers.set('token2', 'lol');
if (localStorage.getItem('token1')) {
headers.set('token3', 'gosh');
}
}
const headers = new Headers();
this.myLovellyHeaders(headers);
Angular 4.3+
Set multi headers in Interceptor:
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpHeaders
} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {environment} from '../../../../environments/environment';
export class SetHeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headers = new HttpHeaders({
'Authorization': 'token 123',
'WEB-API-key': environment.webApiKey,
'Content-Type': 'application/json'
});
const cloneReq = req.clone({headers});
return next.handle(cloneReq);
}
}