0
0
Angularframework~5 mins

POST requests in Angular

Choose your learning style9 modes available
Introduction

POST requests send data from your app to a server. They help you save or update information online.

When a user submits a form with their details.
When you want to add a new item to a list on the server.
When uploading a file or image from your app.
When sending data that changes something on the server.
When you need to send complex data like JSON objects.
Syntax
Angular
this.http.post(url, body, options).subscribe(response => {
  // handle response
});
Use Angular's HttpClient service to make POST requests.
The 'body' is the data you want to send, usually an object.
Examples
Sends a new user object to the server and logs the response.
Angular
this.http.post('https://api.example.com/users', {name: 'Anna', age: 25}).subscribe(response => {
  console.log(response);
});
Sends JSON data with headers specifying the content type.
Angular
const headers = { 'Content-Type': 'application/json' };
this.http.post('https://api.example.com/data', {key: 'value'}, {headers}).subscribe(res => {
  console.log('Data saved');
});
Sample Program

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.

Angular
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);
      });
  }
}
OutputSuccess
Important Notes

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.

Summary

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.