Skip to content

Instantly share code, notes, and snippets.

@lokitoth
Created May 20, 2017 03:34
Show Gist options
  • Save lokitoth/d71794061e7e03bb8c1bf73648d6733d to your computer and use it in GitHub Desktop.
Save lokitoth/d71794061e7e03bb8c1bf73648d6733d to your computer and use it in GitHub Desktop.
Angular2 TypeScript REST client base class
import { Http, Response, Headers, RequestOptions } from "@angular/http";
import * as Rx from "rxjs/Rx";
export abstract class HttpClient {
constructor(private http: Http) {
}
protected referenceStringEncode(referenceString: string): string {
return referenceString.replace("/", "%2F");
}
protected getRequest<TResult>(endpoint: string): Rx.Observable<TResult> {
return this.http.get(endpoint)
.map(response => <TResult>response.json())
.catch(response => this.handleError(response));
}
protected deleteRequest<TResult>(endpoint: string): Rx.Observable<TResult> {
return this.http.delete(endpoint)
.map(response => <TResult>response.json())
.catch(response => this.handleError(response));
}
protected postRequest<TInput, TResult>(endpoint: string, value: TInput): Rx.Observable<TResult> {
let body = JSON.stringify(value);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(endpoint, body, options)
.map(response => <TResult>response.json())
.catch(response => this.handleError(response));
}
protected putRequest<TInput, TResult>(endpoint: string, value: TInput): Rx.Observable<TResult> {
let body = JSON.stringify(value);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.put(endpoint, body, options)
.map(response => <TResult>response.json())
.catch(response => this.handleError(response));
}
protected patchRequest<TInput, TResult>(endpoint: string, value: TInput): Rx.Observable<TResult> {
let body = JSON.stringify(value);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.patch(endpoint, body, options)
.map(response => <TResult>response.json())
.catch(response => this.handleError(response));
}
private handleError<TResult>(response: Response) {
return Rx.Observable.throw(response.json());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment