Avijit Gupta Avijit Gupta - 1 year ago 2587
AngularJS Question

Angular2 - set headers for every request

I need to set some Authorization headers after the user has logged in, for every subsequent request.


To set headers for a particular request,

import {Headers} from 'angular2/http';
var headers = new Headers();
headers.append(headerName, value);

// HTTP POST using these headers
this.http.post(url, data, {
headers: headers
// do something with the response


But it would be not be feasible to manually set request headers for every request in this way.

How do I set the headers set once the user has logged in, and also remove those headers on logout?

Answer Source

HTTP interceptors aren't supported in Angular 2 but there is an interesting discussion on this subject in the Angular Github: https://github.com/angular/angular/issues/2684.

To answer, you question you could provide a service that wraps the original Http object from Angular2. Something like described below.

import {Http, Headers} from 'angular2/http';

export class HttpClient {
  constructor(http: Http) {
    this.http = http;

  createAuthorizationHeader(headers:Headers) {
    headers.append('Authorization', 'Basic ' +

  get(url) {
    let headers = new Headers();
    return this.http.get(url, {
      headers: headers

  post(url, data) {
    let headers = new Headers();
    return this.http.post(url, data, {
      headers: headers

And instead of injecting the Http object you could inject this one.

import {HttpClient} from './http-client';

export classMyComponent {
  constructor(httpClient: HttpClient) {
    this.httpClient = httpClient;

  handleSomething() {
    this.httpClient.post(url, data)

I also think that something could be done using mult providers for the Http class by providing your own class extending the Http one... See this link: http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html.

Hope it helps you, Thierry

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download