I need to set some Authorization headers after the user has logged in, for every subsequent request.
To set headers for a particular request,
Although I'm answering this very late but if anyone is seeking an easier solution.
We can use angular2-jwt. angular2-jwt is useful automatically attaching a JSON Web Token (JWT) as an Authorization header when making HTTP requests from an Angular 2 app.
We can set global headers with advanced configuration option
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig({
tokenName: 'token',
tokenGetter: (() => sessionStorage.getItem('token')),
globalHeaders: [{'Content-Type':'application/json'}],
}), http, options);
}
And sending per request token like
getThing() {
let myHeader = new Headers();
myHeader.append('Content-Type', 'application/json');
this.authHttp.get('http://example.com/api/thing', { headers: myHeader })
.subscribe(
data => this.thing = data,
err => console.log(error),
() => console.log('Request Complete')
);
// Pass it after the body in a POST request
this.authHttp.post('http://example.com/api/thing', 'post body', { headers: myHeader })
.subscribe(
data => this.thing = data,
err => console.log(error),
() => console.log('Request Complete')
);
}