56 lines
1.6 KiB
TypeScript
56 lines
1.6 KiB
TypeScript
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/timeout';
|
|
import 'rxjs/add/observable/throw';
|
|
|
|
@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('Accept', 'application/json')
|
|
.set('Content-Type', 'application/json');
|
|
}
|
|
|
|
public get httpClient(): HttpClient {
|
|
return this._httpClient;
|
|
}
|
|
|
|
public get<T>(entry: string, params?: {[param: string]: string | string[]}): Observable<T> {
|
|
const headers: HttpHeaders = this.httpHeaders;
|
|
|
|
return this._httpClient
|
|
.get<T>(Location.joinWithSlash(this._baseURL, entry), {
|
|
headers: headers,
|
|
params: params,
|
|
responseType: 'json',
|
|
})
|
|
.map(response => response)
|
|
.catch((error: HttpErrorResponse) => Observable.throw(error.error));
|
|
}
|
|
|
|
public post<T>(entry: string, body: any | null, params?: {[param: string]: string | string[]}): Observable<T> {
|
|
const headers: HttpHeaders = this.httpHeaders;
|
|
|
|
return this._httpClient
|
|
.post<T>(Location.joinWithSlash(this._baseURL, entry), body, {
|
|
headers: headers,
|
|
params: params,
|
|
responseType: 'json',
|
|
})
|
|
.map(response => response)
|
|
.catch((error: HttpErrorResponse) => Observable.throw(error.error));
|
|
}
|
|
|
|
}
|