Angular 17 HttpClient POST Example

Angular 17 HttpClient POST Example

To send an HTTP POST request in Angular 17 using HttpClient; Just open app.module.ts typescript file and import the HttpClient module in it and use the httpClient.POST() method to make http post requests to the server in Angular.

Send form data to a server in JSON, text, or any other format from the Angular 17 application using post() method of the HttpClient module. In this guide, we will send form data by making http POST request to server using httpClient.post() method in Angular applications.

Angular HttpClient Post Example

Steps to use HttpClient.post() to perform HTTP POST requests in Angular application:

Step 1: Set up New Angular Project

Start the terminal or cmd and run the ng new myApp --no-standalone command into it to create new angular project; as follows:

ng new myApp --no-standalone

Step 2: Import HttpClientModule

To import HttpClientModule in app.module.ts file, which is in src/app directory; like the following:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
  
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';

  
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 3: Create a Service to Send HTTP POST requests

Run ng g s services/post command on cmd or terminal to create service to make http POST requests on server; as follows:

ng g s services/post

Navigate to src/app/services/ folder and send http POST requests on the server from the client side using httpClient.post() method in post.service.ts file; like following:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
  
@Injectable({
  providedIn: 'root'
})
export class PostService {
  private url = 'https://jsonplaceholder.typicode.com/posts';
   
  constructor(private httpClient: HttpClient) { }
  
  createPost(data: any){
    return this.httpClient.post(this.url, data);
  }
  
}

Step 4: Use Service in Component

Open app.component.ts from the src/app folder and use a service like following into it to use the HTTPClient.post() method to fetch data from a server via client requests:

import { Component, OnInit } from '@angular/core';
import { PostService } from './services/post.service';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  postData = {
    title: '',
    body: ''
  };
  
  constructor(private service:PostService) {}
  
  createPost() {
    this.service.createPost(this.postData).subscribe(
      response => {
        console.log('Post created successfully:', response);
         alert('Post created successfully');
      },
      error => {
        console.error('Error creating post:', error);
      }
    );
  }
}

Step 5: Show HTTP POST Requests Response

To show httpClient POST request response in html template, simply navigate to the src/app/ folder and open app.component.html and show it like the following:

<h1>Angular httpclient POST Request Example - Tutsmake.com</h1>
  
<form (submit)="createPost()">
  <label>Title:</label><br>
  <input type="text" [(ngModel)]="postData.title" name="title" required><br>
  <label>Body:</label><br>
  <textarea [(ngModel)]="postData.body" name="body" required></textarea><br>
  <button type="submit">Create Post</button>
</form>

Step 6: Run Angular App

Run ng serve on cmd or terminal window to start angular app:

ng serve

Open your web browser, and type the given URL into it: as follows:

http://localhost:4200

Conclusion

That’s it; you have learned how to use HttpClient.post() method to make http post request to send data on server in Angular.

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *