import { Injectable, Inject } from '@angular/core'; import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { Location } from '@angular/common'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/timeout'; import 'rxjs/add/observable/throw'; import { ErrorResponse } from './error-response'; @Injectable() export class RESTService { private readonly httpHeaders: HttpHeaders; constructor( @Inject('REST_BASE_URL') private _baseURL: string, @Inject(HttpClient) private _httpClient: HttpClient, ) { this.httpHeaders = new HttpHeaders() .set('Content-Type', 'application/json'); } public get httpClient(): HttpClient { return this._httpClient; } public get(entry: string, params?: {[param: string]: string | string[]}): Observable { const headers: HttpHeaders = this.httpHeaders; return this._httpClient .get(Location.joinWithSlash(this._baseURL, entry), { headers: headers, params: params, responseType: 'json', }) .map((response: string) => JSON.parse(response)) .catch((error: HttpErrorResponse) => Observable.throw(ErrorResponse.restError(error))); } public post(entry: string, body: any | null, params?: {[param: string]: string | string[]}): Observable { const headers: HttpHeaders = this.httpHeaders; return this._httpClient .post(Location.joinWithSlash(this._baseURL, entry), body, { headers: headers, params: params, responseType: 'json', }) .map((response: string) => JSON.parse(response)) .catch((error: HttpErrorResponse) => Observable.throw(ErrorResponse.restError(error))); } }