Making GET and POST Requests
Now that you have HttpClient set up, let's make actual requests. The most common HTTP methods are GET (retrieve data) and POST (send new data).
GET Request
Use
http.get() to fetch data. It typically returns an Observable of an array or object.getPosts(): Observable {
return this.http.get('https://jsonplaceholder.typicode.com/posts');
}
You can add query parameters using params option:import { HttpParams } from '@angular/common/http';
let params = new HttpParams().set('userId', '1');
return this.http.get('https://jsonplaceholder.typicode.com/posts', { params });
POST Request
Use
http.post() to send new data. The second argument is the body.addPost(post: Post): Observable {
return this.http.post('https://jsonplaceholder.typicode.com/posts', post);
}
PUT and DELETE
Similar syntax for update and delete.
updatePost(post: Post): Observable {
return this.http.put(`https://jsonplaceholder.typicode.com/posts/${post.id}`, post);
}
deletePost(id: number): Observable {
return this.http.delete(`https://jsonplaceholder.typicode.com/posts/${id}`);
}
Using in a Component
Inject the service and subscribe.
@Component({...})
export class PostComponent {
posts: Post[] = [];
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getPosts().subscribe(data => {
this.posts = data;
});
}
addPost(title: string) {
const newPost = { title, body: '...', userId: 1 };
this.dataService.addPost(newPost).subscribe(created => {
this.posts.push(created);
});
}
}
Two Minute Drill
- GET retrieves data; POST sends new data.
- Use HttpParams for query parameters.
- PUT updates existing data; DELETE removes data.
- All methods return Observables – subscribe in components.
- Always unsubscribe to avoid memory leaks (or use async pipe).
Need more clarification?
Drop us an email at career@quipoinfotech.com
