import { HttpClient } from "@angular/common/http"; import { Router } from "@angular/router"; import { Injectable } from "@angular/core"; @Injectable({ providedIn: "root", }) export class RequestService { constructor(private http: HttpClient, private router: Router) {} public post( apiPath: string, body: any, successFunction: Function, errorFunction: Function | null = null ) { let url = this.obtainUrl(apiPath); let observable = this.http.post(url, body).subscribe( (answer: any) => { successFunction(answer); }, (error: any) => { if (errorFunction === null) this.handleError(error); else errorFunction(error); } ); } public get( apiPath: string, body: any, successFunction: Function, errorFunction: Function | null = null ) { let url = this.obtainUrl(apiPath); let observable = this.http.get(url, body).subscribe( (answer: any) => { successFunction(answer); }, (error: any) => { if (errorFunction === null) this.handleError(error); else errorFunction(error); } ); } public postFiles( apiPath: string, files: File[], successFunction: Function, errorFunction: Function | null = null ) { if (!files || files.length === 0) { throw "Need to select at least one file"; } const formData = new FormData(); for (let fileIndex = 0; fileIndex < files.length; fileIndex++) { formData.append("file" + fileIndex, files[fileIndex]); } let url = this.obtainUrl(apiPath); let observable = this.http.post(url, formData).subscribe( (answer: any) => { successFunction(answer); }, (error: any) => { if (errorFunction === null) this.handleError(error); else errorFunction(error); } ); } private obtainUrl(apiPath: string): string { let hostString = window.location.host; let protocol = window.location.protocol; return protocol + "//" + hostString + "/api/" + apiPath; } private handleError(answer: any): void { if (answer.status == 401) { console.log("Deine Sitzung konnte nicht gefunden werden"); this.router.navigate(["/auth"]); return; } if (answer.status == 403) { this.showSnackBar("Du bist nicht für diese Aktion autorisiert", "Ok"); return; } try { let errorObject = answer.error.error; if (errorObject.hasOwnProperty("message")) { throw errorObject.message.toString(); } if (errorObject.hasOwnProperty("code")) { throw errorObject.code.toString(); } } catch (error: any) { this.showSnackBar(error.toString(), "Ok"); } } private showSnackBar(message: string, action?: string) { /*this.snackBar.open(message.toString(), action, { duration: 3000, });*/ console.log(message); } }