Skip to content

Adding headers to http requests in Angular2

One of the common scenarios where the ability to add headers to angular http requests comes in handy is authentication API calls using tokens. It is very easy to add headers to individual calls like below but it’s a little bit more work to do so for all http requests.

Adding header to single http call

import {Headers} from 'angular2/http';
var headers = new Headers();
headers.append('CustomHeader', 'CustomHeaderValue');
this.http.get('https://api.github.com/users', {
headers: headers
})

Adding header to all http calls

For this, we have to extend the BaseRequestOptions class. There are some differences between extending BaseRequestOptions and RequestOptions- should research this someday.

Below code gets some value from a different service and sets it as ‘CustomHeader’. super(); is needed in the constructor for derived classes.

request.service.ts

import {BaseRequestOptions} from 'angular2/http';
@Injectable()
export class AuthRequestOptions extends BaseRequestOptions {
constructor(private _someService: SomeService) {
super();
}
// doesn't add this header if below function returns null or undefined
headers = new Headers({
'CustomHeader': this._someService.getValue()
});
}
@Injectable()
export class RequestService {
constructor(private http: Http) { }
getRequest(){
return this.http.get('https://api.github.com/users')
.map(res => res.json())
.catch();
}
}

Now, we have to configure Angular to use the above class instead of the default RequestOptions.

app.module.ts

import { NgModule } from '@angular/core';
import { RequestOptions } from '@angular/http';
import { RequestService, AuthRequestOptions } from './request.service';
@NgModule({
// More settings
providers: [
RequestService,
{provide: RequestOptions, useClass: AuthRequestOptions }
],
})
export class AppModule { }

Lot more information can be found here.