diff --git a/src/config/environment.ts b/src/config/environment.ts new file mode 100644 index 0000000..be42646 --- /dev/null +++ b/src/config/environment.ts @@ -0,0 +1,4 @@ +export const environment = { + apiUrl: 'http://localhost:5269/api/v1/', + production: false +} diff --git a/src/services/api.service.ts b/src/services/api.service.ts new file mode 100644 index 0000000..4726182 --- /dev/null +++ b/src/services/api.service.ts @@ -0,0 +1,84 @@ +import {Injectable} from '@angular/core'; +import {catchError, Observable, throwError} from "rxjs"; +import {HttpClient} from "@angular/common/http"; +import {NotifyColor, OpenNotifyService} from "@service/open-notify.service"; +import {environment} from "@/config/environment"; + +@Injectable({ + providedIn: 'root' +}) + +export class ApiService { + constructor(private http: HttpClient, private notify: OpenNotifyService) { + } + + private urlApi = environment.apiUrl; + + get(endpoint: string): Observable { + return this.http.get(this.urlApi + endpoint).pipe( + catchError(error => { + this.handleError(error); + return throwError(error); + }) + ); + } + + post(endpoint: string, data: any): Observable { + return this.http.post(this.urlApi + endpoint, data).pipe( + catchError(error => { + this.handleError(error); + return throwError(error); + }) + ); + } + + put(endpoint: string, data: any): Observable { + return this.http.put(this.urlApi + endpoint, data).pipe( + catchError(error => { + this.handleError(error); + return throwError(error); + }) + ); + } + + delete(endpoint: string): Observable { + return this.http.delete(this.urlApi + endpoint).pipe( + catchError(error => { + this.handleError(error); + return throwError(error); + }) + ); + } + + private handleError(error: any): void { + let message: string; + if (error.error instanceof ErrorEvent) { + message = `Произошла ошибка: ${error.error.message}`; + } else { + switch (error.status) { + case 0: + message = 'Неизвестная ошибка. Пожалуйста, попробуйте позже.'; + break; + case 400: + message = 'Ошибка запроса. Пожалуйста, проверьте отправленные данные.'; + break; + case 401: + message = 'Ошибка авторизации. Пожалуйста, выполните вход с правильными учетными данными.'; + break; + case 403: + message = 'Отказано в доступе. У вас нет разрешения на выполнение этого действия.'; + break; + case 404: + message = 'Запрашиваемый ресурс не найден.'; + break; + case 500: + message = 'Внутренняя ошибка сервера. Пожалуйста, попробуйте позже.'; + break; + default: + message = `Сервер вернул код ошибки: ${error.status}`; + break; + } + } + this.notify.open(message, NotifyColor.Danger); + } +}