I need to set some Authorization headers after the user has logged in, for every subsequent request.
To set headers for a particular request,
This is how I did for setting token with every request.
import { RequestOptions, BaseRequestOptions, RequestOptionsArgs } from '@angular/http';
export class CustomRequestOptions extends BaseRequestOptions {
constructor() {
super();
this.headers.set('Content-Type', 'application/json');
}
merge(options?: RequestOptionsArgs): RequestOptions {
const token = localStorage.getItem('token');
const newOptions = super.merge(options);
if (token) {
newOptions.headers.set('Authorization', `Bearer ${token}`);
}
return newOptions;
}
}
And register in app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
{ provide: RequestOptions, useClass: CustomRequestOptions }
],
bootstrap: [AppComponent]
})
export class AppModule { }