common-cents-web/src/app/services/http.service.ts
2026-02-23 00:19:30 -06:00

40 lines
1.3 KiB
TypeScript

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class HttpService {
public constructor(private httpClient: HttpClient) { }
public async get<T>(url: string): Promise<T> {
return this.request<T>(url, 'get');
}
public async post<T>(url: string, body?: any): Promise<T> {
return this.request<T>(url, 'post', body);
}
public async put<T>(url: string, body?: any): Promise<T> {
return this.request<T>(url, 'put', body);
}
public async delete<T>(url: string): Promise<T> {
return this.request<T>(url, 'delete');
}
private async request<T>(url: string, method: 'get' | 'post' | 'put' | 'delete', body?: any): Promise<T> {
const headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' };
switch (method) {
case 'post':
return firstValueFrom(this.httpClient.post<T>(url, body, { headers }));
case 'put':
return firstValueFrom(this.httpClient.put<T>(url, body, { headers }));
case 'delete':
return firstValueFrom(this.httpClient.delete<T>(url, { headers }));
default:
return firstValueFrom(this.httpClient.get<T>(url, { headers }));
}
}
}