Samuel Fraga Mateos Samuel Fraga Mateos - 1 year ago 181
HTTP Question

Angular 2 interceptor is not working properly

I'm trying to create a custom http class that extends Http to work like AngularJS interceptors on Angular 2. I followed other Stackoverflow questions and some several tutorials but I always get the same error and I can't find the solution.

I have the following Http interceptor:

import { Injectable } from '@angular/core';
import { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs, Response, Headers, Request } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

export class CustomHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);

request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
options = new RequestOptions();
let headers = new Headers();
headers.append('X-Auth-Token', 'Bearer ' + localStorage.getItem('access-token'));
options.headers = headers;
return super.request(url, options);

And I've add it to the app.module like this:

providers: [{
provide: Http,
useFactory: loadCustomHttp,
deps: [XHRBackend, RequestOptions]

export function loadCustomHttp(backend: XHRBackend, defaultOptions: RequestOptions) {
return new CustomHttp(backend, defaultOptions);

I don't get any error with this configuration but when I do any request, I get a 401 because the authentication header wasn't added. A sample request could be:

import { Http } from '@angular/http';

getExample() {
let url = this.urlBase + '/test';

return this.http.get(url);

Any help would be much appreciated, thanks in advance :)

Answer Source

The url could be one of two different types, string or Request, so

request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
let token = localStorage.getItem('access-token');

if (token) {
  if (typeof url === 'string') {
    if (!options) {
      options = { headers: new Headers() };
    options.headers.set('Authorization', `Bearer ${token}`);
    console.log('Url is string', options.headers.get('Authorization'));
  } else {
    url.headers.set('Authorization', `Bearer ${token}`);
    console.log('Url is Request', url.headers.get('Authorization'));

return super.request(url, options);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download