I need to set some Authorization headers after the user has logged in, for every subsequent request.
To set headers for a particular request,
Here is an improved version of the accepted answer, updated for Angular2 final :
import {Injectable} from "@angular/core";
import {Http, Headers, Response, Request, BaseRequestOptions, RequestMethod} from "@angular/http";
import {I18nService} from "../lang-picker/i18n.service";
import {Observable} from "rxjs";
@Injectable()
export class HttpClient {
constructor(private http: Http, private i18n: I18nService ) {}
get(url:string):Observable {
return this.request(url, RequestMethod.Get);
}
post(url:string, body:any) {
return this.request(url, RequestMethod.Post, body);
}
private request(url:string, method:RequestMethod, body?:any):Observable{
let headers = new Headers();
this.createAcceptLanguageHeader(headers);
let options = new BaseRequestOptions();
options.headers = headers;
options.url = url;
options.method = method;
options.body = body;
options.withCredentials = true;
let request = new Request(options);
return this.http.request(request);
}
// set the accept-language header using the value from i18n service that holds the language currently selected by the user
private createAcceptLanguageHeader(headers:Headers) {
headers.append('Accept-Language', this.i18n.getCurrentLang());
}
}
Of course it should be extended for methods like delete and put if needed (I don't need them yet at this point in my project).
The advantage is that there is less duplicated code in the get/post/... methods.
Note that in my case I use cookies for authentication. I needed the header for i18n (the Accept-Language header) because many values returned by our API are translated in the user's language. In my app the i18n service holds the language currently selected by the user.