How to Make POST Request in Angular: Simple Guide
In Angular, use the
HttpClient service to make a POST request by calling http.post(url, body). Import HttpClientModule in your app module and inject HttpClient in your component or service to send data to a server.Syntax
The basic syntax for a POST request in Angular uses the HttpClient service's post method.
url: The endpoint where you send the data.body: The data object you want to send.options(optional): Additional settings like headers.
typescript
this.http.post(url, body, options?)Example
This example shows how to send a POST request to a server with JSON data and handle the response.
typescript
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-post-example', template: `<button (click)="sendPost()">Send POST Request</button><p>{{responseMessage}}</p>` }) export class PostExampleComponent { responseMessage = ''; constructor(private http: HttpClient) {} sendPost() { const url = 'https://jsonplaceholder.typicode.com/posts'; const body = { title: 'foo', body: 'bar', userId: 1 }; this.http.post(url, body).subscribe({ next: (response) => { this.responseMessage = 'Post successful: ' + JSON.stringify(response); }, error: (error) => { this.responseMessage = 'Error: ' + error.message; } }); } }
Output
When clicking the button, the page shows: Post successful: {"id":101,"title":"foo","body":"bar","userId":1}
Common Pitfalls
Common mistakes when making POST requests in Angular include:
- Not importing
HttpClientModuleinAppModule, causing injection errors. - Forgetting to subscribe to the
postobservable, so the request never runs. - Not setting correct headers when needed, like
Content-Type: application/json. - Ignoring error handling, which can hide request failures.
typescript
/* Wrong: Missing subscription, request won't send */ this.http.post(url, body); /* Right: Subscribe to execute and handle response */ this.http.post(url, body).subscribe(response => console.log(response));
Quick Reference
Remember these key points for POST requests in Angular:
- Import
HttpClientModulein your app module. - Inject
HttpClientin your component or service. - Use
http.post(url, body)and always subscribe to the observable. - Handle errors with
subscribeerror callback.
Key Takeaways
Always import HttpClientModule in your Angular app module before using HttpClient.
Use HttpClient.post(url, body) and subscribe to send the POST request and receive responses.
Handle errors in the subscribe error callback to catch request failures.
Set headers if your API requires specific content types or authentication.
Without subscribing, the POST request will not be executed.