In my Angular2 application, I am setting header values to each and every request using CustomRequestOptions class which extends BaseRequestOptions.
@Injectable()
export class CustomRequestOptions extends BaseRequestOptions {
constructor(private _globals: Globals) {
super();
this.headers.set('Content-Type', 'application/json');
this.headers.set('X-Requested-By', 'Angular 2');
}
merge(options?: RequestOptionsArgs): RequestOptions {
// can I access the headers here I have set when the request is made ?
// and then conditionally set Content-Type
var newOptions = super.merge(options);
let hdr = this._globals.getAuthorization();
newOptions.headers.set("Authorization", hdr);
return newOptions;
}
}
As you can see, Content Type is set to application/json.
Now I have a requirement to upload a photo to the server. The Content type has to be cleared for that request only.
The way I thought of using is setting some header value to the request, getting that value inside merge method and conditionally clear the content type header.
Setting a custom header when the request is declared:-
let formData: FormData = new FormData();
formData.append('file', photoToSave);
let headers = new Headers();
//setting a custom header
headers.append('from', 'photo-upload');
let options = new RequestOptions();
options.headers = headers;
let savedPath = this._http
.post(this._endpointUrl + "save-photo", formData, options)
.map(
res => {
return res.json();
}
)
.catch(handleError);
Accessing the added header in merge method. This is where I have the problem. Can I do what I am trying to do. ? I tried following as a starting point. But the accessed headers are null. See the comment in the code.
merge(options?: RequestOptionsArgs): RequestOptions {
console.log("options header = " + options.headers); //this prints null
console.log("options body = " + options.body);
var newOptions = super.merge(options);
if(from header equal to 'photo-upload'){
newOptions.headers.set('Content-Type', '');
}else{
newOptions.headers.set('Content-Type', 'application/json');
}
let hdr = this._globals.getAuthorization();
newOptions.headers.set("Authorization", hdr);
return newOptions;
}
Now my question is about the validity of what I am trying to do. If it is not valid, please point me out a way to do this. Thank You..!