refactor: move contact servicesto services folder
This commit is contained in:
47
src/app/services/contact.service.ts
Normal file
47
src/app/services/contact.service.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user