Adding headers to http requests in Angular2

1 minute read

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('', {
  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.


import {BaseRequestOptions} from 'angular2/http';

export class AuthRequestOptions extends BaseRequestOptions {

    constructor(private _someService: SomeService) {

    // doesn't add this header if below function returns null or undefined
    headers = new Headers({
        'CustomHeader': this._someService.getValue()

export class RequestService {

    constructor(private http: Http) { }

        return this.http.get('')
                   .map(res => res.json())


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


import { NgModule } from '@angular/core';
import { RequestOptions } from '@angular/http';
import { RequestService, AuthRequestOptions } from './request.service';

  // More settings
  providers: [
    {provide: RequestOptions, useClass: AuthRequestOptions }
export class AppModule { }

Lot more information can be found here.

Leave a Comment