Standalone API Service for Data Retrieval
Create a standalone Angular service that encapsulates all HTTP requests for CRUD operations, allowing for easy import and use by any component.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class DataService {
private baseUrl: string = 'https://api.example.com/data';
constructor(private http: HttpClient) {}
// Retrieve all items
getAll(): Observable<any> {
return this.http.get(this.baseUrl);
}
// Retrieve single item by id
getById(id: number): Observable<any> {
return this.http.get(`${this.baseUrl}/${id}`);
}
// Create new item
create(item: any): Observable<any> {
return this.http.post(this.baseUrl, item);
}
// Update existing item
update(id: number, item: any): Observable<any> {
return this.http.put(`${this.baseUrl}/${id}`, item);
}
// Delete item by id
delete(id: number): Observable<any> {
return this.http.delete(`${this.baseUrl}/${id}`);
}
}
This code defines an Angular service called 'DataService'. It uses Angular's HttpClient to perform HTTP requests to a 'baseUrl'. CRUD operations are encapsulated within it: getAll() retrieves all items, getById(id) retrieves an item by its ID, create(item) creates a new item, update(id, item) updates an existing item, and delete(id) deletes an item by ID. It returns observables making it suitable for easy integration with Angular components.