First, import the HttpClientModule
in app.module.ts
:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
bootstrap: [AppComponent]
})
export class AppModule {}
It’s a good practice to separate API calls into a service.
Run the command:
ng generate service api
Modify api.service.ts
:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private apiUrl = 'https://jsonplaceholder.typicode.com/posts'; // Sample API
constructor(private http: HttpClient) {}
// GET Request
getPosts(): Observable<any> {
return this.http.get(this.apiUrl);
}
// POST Request
createPost(postData: any): Observable<any> {
return this.http.post(this.apiUrl, postData);
}
// PUT Request
updatePost(id: number, updatedData: any): Observable<any> {
return this.http.put(`${this.apiUrl}/${id}`, updatedData);
}
// DELETE Request
deletePost(id: number): Observable<any> {
return this.http.delete(`${this.apiUrl}/${id}`);
}
}
Modify app.component.ts
:
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
posts: any[] = [];
constructor(private apiService: ApiService) {}
ngOnInit() {
this.loadPosts();
}
loadPosts() {
this.apiService.getPosts().subscribe((data) => {
this.posts = data;
});
}
addPost() {
const newPost = { title: 'New Post', body: 'This is a test post' };
this.apiService.createPost(newPost).subscribe((data) => {
this.posts.push(data);
});
}
deletePost(id: number) {
this.apiService.deletePost(id).subscribe(() => {
this.posts = this.posts.filter((post) => post.id !== id);
});
}
}
Modify app.component.html
:
<h2>Posts</h2>
<ul>
<li *ngFor="let post of posts">
{{ post.title }}
<button (click)="deletePost(post.id)">Delete</button>
</li>
</ul>
<button (click)="addPost()">Add Post</button>
Use catchError
from RxJS to handle errors in api.service.ts
:
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
getPosts(): Observable<any> {
return this.http.get(this.apiUrl).pipe(
catchError((error) => {
console.error('Error fetching posts:', error);
return throwError(error);
})
);
}
✔ Angular HttpClient makes API calls simple and efficient.
✔ Use an API service to organize API requests.
✔ Handle GET, POST, PUT, DELETE operations efficiently.
✔ Implement error handling for better user experience.
✔ This approach helps in building dynamic and scalable Angular applications. 🚀