1

I created an interceptor for authentication in angular 2 .The interceptor code is as shown below,

import {
  Injectable
} from '@angular/core';
import {
  Http,
  XHRBackend,
  RequestOptions,
  Request,
  RequestOptionsArgs,
  Response,
  Headers
} from '@angular/http';
import {
  Observable
} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class HttpService extends Http {
  constructor(public headers: Headers,
    public backend: XHRBackend,
    options: RequestOptions) {
    super(backend, options);
    let token = localStorage.getItem('realtoken');;
    console.log(token);
    options.headers.set('Authorization', `Bearer ${token}`);
  }
  get(url: string, options ? : RequestOptionsArgs): Observable < Response > {
    // this.headers=new Headers();
    //this.headers.append('Content-Type','application/json');
    let token = localStorage.getItem('realtoken');
    if (typeof url === 'string') {
      if (!options) {
        options = {
          headers: this.headers
        };
      }
      options.headers.set('Authorization', `Bearer ${token}`);
    }
    return super.get(url, options).catch(this.catchAuthError(this));
  }

  private catchAuthError(self: HttpService) {
    return (res: Response) => {
      console.log(res);
      if (res.status === 401 || res.status === 403) {
        console.log(res);
      }
      return Observable.throw(res);
    };
  }

}
But when I inject this http interceptor service in other services to call the backend,I get DI error stating there is no provider for headers, my service code is as shown below

@Injectable()
export class EmployeeService {
  private res: Response
  private options: any;
  constructor(private _httpService: HttpService) {

  }
  getEmployeeCollection(): any {
    let url: string = Constants.DOMAIN + Constants.HOME_ROUTE;
    console.log('url', url);
    return this._httpService.get(url).map(res => res.json()).catch(this._errorHandler);
  }
  _errorHandler(error: Response) {
    return Observable.throw(error);
  }
}

Could anyone suggest me where I am wrong? As I am a beginner I couldn't figure out where I am wrong.

0 Answers0