48 lines
1.5 KiB
TypeScript
48 lines
1.5 KiB
TypeScript
import { HttpClient } from '@angular/common/http';
|
|
import { inject, Injectable } from '@angular/core';
|
|
import { environment } from '../../environments/environment';
|
|
import { ContactDTO } from '../models/ContactDTO';
|
|
import { Response } from '../models/Response';
|
|
import { BehaviorSubject, map, switchMap, tap } from 'rxjs';
|
|
|
|
@Injectable({
|
|
providedIn: 'root',
|
|
})
|
|
export class ContactService {
|
|
private readonly httpClient = inject(HttpClient);
|
|
private readonly contacts = new BehaviorSubject<ContactDTO[]>([]);
|
|
readonly contacts$ = this.contacts.asObservable();
|
|
|
|
delete(id: number) {
|
|
return this.httpClient
|
|
.delete<Response<string>>(`${environment.apiUrl}/contacts/${id}`)
|
|
.pipe(switchMap(() => this.getAll()));
|
|
}
|
|
|
|
findById(id: string) {
|
|
return this.httpClient.get<Response<ContactDTO | null>>(`${environment.apiUrl}/contacts/${id}`);
|
|
}
|
|
|
|
getAll() {
|
|
return this.httpClient
|
|
.get<Response<ContactDTO[] | null>>(environment.apiUrl + '/contacts')
|
|
.pipe(
|
|
map((response) => response.data ?? []),
|
|
tap((contacts) => this.contacts.next(contacts))
|
|
);
|
|
}
|
|
|
|
save(contact: ContactDTO) {
|
|
return this.httpClient
|
|
.post<Response<ContactDTO[] | null>>(environment.apiUrl + '/contacts', contact)
|
|
.pipe(switchMap(() => this.getAll()));
|
|
}
|
|
|
|
update(contact: ContactDTO) {
|
|
return this.httpClient.put<Response<ContactDTO[] | null>>(
|
|
`${environment.apiUrl}/contacts/${contact.id}`,
|
|
contact
|
|
);
|
|
}
|
|
}
|