feat: add api service

This commit is contained in:
Polianin Nikita 2024-02-17 08:00:58 +03:00
parent 272c76cfa8
commit d26c3d885b
2 changed files with 88 additions and 0 deletions

View File

@ -0,0 +1,4 @@
export const environment = {
apiUrl: 'http://localhost:5269/api/v1/',
production: false
}

View File

@ -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<Type>(endpoint: string): Observable<Type> {
return this.http.get<Type>(this.urlApi + endpoint).pipe(
catchError(error => {
this.handleError(error);
return throwError(error);
})
);
}
post<Type>(endpoint: string, data: any): Observable<Type> {
return this.http.post<Type>(this.urlApi + endpoint, data).pipe(
catchError(error => {
this.handleError(error);
return throwError(error);
})
);
}
put<Type>(endpoint: string, data: any): Observable<Type> {
return this.http.put<Type>(this.urlApi + endpoint, data).pipe(
catchError(error => {
this.handleError(error);
return throwError(error);
})
);
}
delete<Type>(endpoint: string): Observable<Type> {
return this.http.delete<Type>(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);
}
}