Introduction
POST requests send data from your app to a server. They help you save or update information online.
POST requests send data from your app to a server. They help you save or update information online.
this.http.post(url, body, options).subscribe(response => { // handle response });
this.http.post('https://api.example.com/users', {name: 'Anna', age: 25}).subscribe(response => { console.log(response); });
const headers = { 'Content-Type': 'application/json' }; this.http.post('https://api.example.com/data', {key: 'value'}, {headers}).subscribe(res => { console.log('Data saved'); });
This Angular component has a button. When clicked, it sends a POST request with user data to a test server. It shows a message when done.
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-post-example', template: ` <button (click)="sendData()">Send Data</button> <p *ngIf="responseMessage">Response: {{ responseMessage }}</p> ` }) export class PostExampleComponent { responseMessage = ''; constructor(private http: HttpClient) {} sendData() { const data = { name: 'John', age: 30 }; this.http.post('https://jsonplaceholder.typicode.com/users', data) .subscribe(response => { this.responseMessage = 'Data sent successfully!'; console.log('Server response:', response); }, error => { this.responseMessage = 'Error sending data.'; console.error(error); }); } }
Always import HttpClientModule in your app module to use HttpClient.
Use subscribe() to handle the server's response or errors.
POST requests usually change data on the server, so use them carefully.
POST requests send data from your app to a server.
Use Angular's HttpClient.post() with a URL and data object.
Handle responses with subscribe() to update your app or show messages.
POST request in Angular's HttpClient?this.http.post('https://api.example.com/items', {name: 'Book'}).subscribe(response => console.log(response));this.http.post('https://api.example.com/data').subscribe(response => console.log(response));Pass the test and this pattern moves unknown