This repository has been archived on 2025-04-11. You can view files and clone it, but cannot push or open issues or pull requests.
bee-frontend-ARCHIVED/src/app/core/services/request.service.ts
2024-08-26 20:19:10 +00:00

115 lines
2.9 KiB
TypeScript

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<any>(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);
}
}