import { RequestErrorHandlerService } from './request-error-handler.service'; import { Response } from "../response/respponse.type"; import { HttpClient, HttpHeaders, HttpParams } from "@angular/common/http"; import { Injectable } from "@angular/core"; @Injectable() export class HttpHandler { constructor( private http: HttpClient, private requestErrorHandlerService: RequestErrorHandlerService ) {} get(url: string, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: 'body'; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }): Promise { return this.http .get>(url, options) .toPromise() .then( (response) => this.handleResponse(response), ) .catch((error) => this.handleError(error)); } post(url: string, data: any, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: 'body'; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }): Promise { return this.http .post>(url, data, options) .toPromise() .then( (response) => this.handleResponse(response), ) .catch((error) => this.handleError(error)); } delete(url: string, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: 'body'; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }): Promise { return this.http .delete>(url, options) .toPromise() .then( (response) => this.handleResponse(response), ) .catch((error) => this.handleError(error)); } private handleResponse(response: Response): T { console.log(response); // this.events.broadcast(NetworkEvent.NETWORK_OK); if (response.success) { return response.data; } else { this.requestErrorHandlerService.responseErrorHandler(response); return undefined; } } private async handleError(error: any) { console.log(error); this.requestErrorHandlerService.networkErrorHandler(error) return null; } }