crusader 48d7216e77 ing
2018-03-07 21:03:36 +09:00

59 lines
1.8 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/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<T>(entry: string, params?: {[param: string]: string | string[]}): Observable<T> {
const headers: HttpHeaders = this.httpHeaders;
return this._httpClient
.get(Location.joinWithSlash(this._baseURL, entry), {
headers: headers,
params: params,
responseType: 'json',
})
.map((response: string) => <T>JSON.parse(response))
.catch((error: HttpErrorResponse) => Observable.throw(ErrorResponse.restError(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(Location.joinWithSlash(this._baseURL, entry), body, {
headers: headers,
params: params,
responseType: 'json',
})
.map((response: string) => <T>JSON.parse(response))
.catch((error: HttpErrorResponse) => Observable.throw(ErrorResponse.restError(error)));
}
}