27. Handling POST Requests
POST requests are used to send data to the server to create a new resource.
Using HttpClient.post()
The post method takes three arguments:
- The URL endpoint.
- The body payload (the data to send).
- (Optional) Configuration options (headers, parameters).
typescript // data.service.ts
interface NewPostData { title: string; body: string; userId: number; }
// Returns the created object (often with a new ID assigned by the server)
createPost(postData: NewPostData) {
return this.http.post
Subscribing and Handling the Response
In the component, we call the service method and subscribe. The response often confirms the resource was created and sometimes includes the full object with server-assigned properties (like an id).
typescript // post-creator.component.ts
newPost: NewPostData = { title: 'Test Title', body: 'Test Body', userId: 1 };
onSubmit() {
this.dataService.createPost(this.newPost).subscribe({
next: (response) => {
console.log('Post created successfully:', response);
alert(Post ID ${response.id} created!);
// Clear form or navigate away
},
error: (err) => {
console.error('Error creating post:', err);
}
});
}
Important: Headers and Content Type
Angular's HttpClient automatically sets the Content-Type header to application/json for POST requests when the payload is a JavaScript object, ensuring the server knows how to parse the data.