Created
January 8, 2021 17:06
-
-
Save nikasepiskveradze/286fa05a0f90aa3d45722154888e2334 to your computer and use it in GitHub Desktop.
Http client example with TS and RXJs
This file contains hidden or 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 {Observable, of} from "rxjs"; | |
import {catchError, map} from "rxjs/operators"; | |
import {ajax} from "rxjs/ajax"; | |
class Http { | |
public get<T extends Object = Object>(url: string, headers?: any): Observable<T> { | |
return ajax.get.apply(undefined, [`${url}`, headers]).pipe(catchError(this.catchError), map(this.map)); | |
} | |
public post<T extends Object = Object>(url: string, body?: any, headers?: any): Observable<T> { | |
return ajax.post.apply(undefined, [`${url}`, body, headers]).pipe(catchError(this.catchError), map(this.map)); | |
} | |
public put<T extends Object = Object>(url: string, body?: any, headers?: any): Observable<T> { | |
return ajax.put.apply(undefined, [`${url}`, body, headers]).pipe(catchError(this.catchError), map(this.map)); | |
} | |
public patch<T extends Object = Object>(url: string, body?: any, headers?: any): Observable<T> { | |
return ajax.patch.apply(undefined, [`${url}`, body, headers]).pipe(catchError(this.catchError), map(this.map)); | |
} | |
public delete<T extends Object = Object>(url: string, headers?: any): Observable<T> { | |
return ajax.delete.apply(undefined, [`${url}`, headers]).pipe(catchError(this.catchError), map(this.map)); | |
} | |
private catchError(err: any, caught: Observable<any>): Observable<any> { | |
// eslint-disable-next-line no-console | |
console.error("httpClient Error:", err.response); | |
return of(err); | |
} | |
private map(data: any) { | |
return data.response; | |
} | |
} | |
export const http = new Http(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment