Created
October 27, 2024 21:38
-
-
Save Mustafa-Omran/0690e2d6b1eebe47c738a148017b9425 to your computer and use it in GitHub Desktop.
Http Client Service In Angular
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 { environment } from '@amaleyat/environments/dev.environment'; | |
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; | |
import { Inject, Injectable, PLATFORM_ID } from '@angular/core'; | |
import { Observable } from 'rxjs/internal/Observable'; | |
import { throwError } from 'rxjs/internal/observable/throwError'; | |
import { catchError } from 'rxjs/internal/operators/catchError'; | |
import { isPlatformBrowser } from '@angular/common'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class HttpClientService { | |
private apiUrl = environment.apiUrl; | |
constructor( | |
private http: HttpClient, | |
@Inject(PLATFORM_ID) private platformId: Object { } | |
private handleError(error: HttpErrorResponse) { | |
if (error.error instanceof ErrorEvent) { | |
console.log('error', error.error.message); | |
} else { | |
const msg = `Backend returned code ${error.status}, ` + `body was: ${error.error}`; | |
console.log('error', msg); | |
} | |
return throwError(() => new Error('Something bad happened; please try again later.')); | |
} | |
private request<T>(url: string, params: any | null, method: string): Observable<T> | any { | |
if (isPlatformBrowser(this.platformId)) { | |
// main body will be sent with every request | |
if (params) { | |
return this.http.request<T>(method, `${this.apiUrl}/${url}`, { body: params }).pipe(catchError(this.handleError)); | |
} | |
return this.http.request<T>(method, `${this.apiUrl}/${url}`).pipe(catchError(this.handleError)); | |
} | |
} | |
get<T>(url: string): Observable<T> { | |
return this.request(`${url}`, null, 'GET'); | |
} | |
getPublicUrl<T>(url: string): Observable<T> { | |
return this.http.request<T>('GET', url).pipe(catchError(this.handleError)); | |
} | |
post<T>(url: string, params: any | null): Observable<T> { | |
return this.request(url, params, 'POST'); | |
} | |
postFile<T>(url: string, params: any | null): Observable<T> { | |
return this.http.post<T>(`${this.apiUrl}/${url}`, params).pipe(catchError(this.handleError)); | |
} | |
put<T>(url: string, params: any | null): Observable<T> { | |
return this.request(url, params, 'PUT'); | |
} | |
delete<T>(url: string): Observable<T> { | |
return this.request(url, {}, 'DELETE'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment