Created
May 20, 2017 03:34
-
-
Save lokitoth/d71794061e7e03bb8c1bf73648d6733d to your computer and use it in GitHub Desktop.
Angular2 TypeScript REST client base class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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