In this article, I am going to explain to you how to post data using angular 2 Http Post request ,  the example which I am going to take out here is submit a comment to the article, for this, I am going to build a separate comments component using JSON placeholder which is a fake rest API and we are going to use only for testing purpose, this API takes JSON Object as an input parameter something like below

    "postId": 1,
    "id": 1,
    "name": "raj",
    "email": "",
    "body": "How to post data to the database using Angular 2 http post request"

Building comments component




The first thing which I am going to do out here is design and build an input form component  for comment’s, if you are new to angular 2 then refer my other article on how to build angular 2 component , the input form component allows end user to enter name, email, body and on click of submit button it sends data to the comments service
Here, I am using angular 2 two-way data binding to read user entered values from the input fields, we need to add two-way binding to name, email and comment box, the syntax for the two-way data binding called is a banana in the box “[()]”, check below Html for two-way binding syntax

<div class="container main-content-area" >
<div id="respond" class="comment-respond">
 <h3 id="reply-title" class="comment-reply-title">Leave a Reply <small><a rel="nofollow" id="cancel-comment-reply-link" style="display:none;">Cancel reply</a></small></h3>
 <form method="post" id="commentform" class="comment-form" novalidate="">
 <p class="comment-notes"><span id="email-notes">Your email address will not be published.</span> Required fields are marked <span class="required">*</span></p>
 <p class="comment-form-comment"><label for="comment">Comment</label> <textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" aria-required="true" required="required" [(ngModel)]="message.message"></textarea></p>
 <p class="comment-form-author"><label for="author">Name <span class="required">*</span></label> <input id="author" name="author" type="text" value="" size="30" maxlength="245" aria-required="true" required="required" [(ngModel)]=""></p>
 <p class="comment-form-email"><label for="email">Email <span class="required">*</span></label> <input id="email" name="email" type="email" value="" size="30" maxlength="100" aria-describedby="email-notes" aria-required="true" required="required" [(ngModel)]=""></p>
 <p class="form-submit"><input name="submit" type="submit" id="submit" class="submit btn btn-default" (click) ="submitPost()" value="Post Comment" style="display: inline-block;">
 <div [hidden] ="!status"> <p>Congratulations {{responseStatus?.name}} , you have successfully posted commentd and the comment id is {{responseStatus?.id}} </p></div>


I have created a separate class Message.ts using typescript, if you are familiar with Java then it is something like a Bean, instead of declaring every property with the @Input directive I have created a separate class and declared with @Input directive this class contains four property’s such as name, email, postId and comments

export class Message
     name: string;
     email: string;


Now build a angular2 component for comments and it should implement ngOnInit method, in this method, I have created a new Message object, the message object takes name and postId which are initialized with default values “keys and strokes” and 1 because we are not dynamically fetching postId and username here, when you integrate with some other component then pass these values dynamically but here as we are using fake JSON API so we have to initialize postId default value to 1 and name of the user to “keys and strokes”
The subscribe takes three functions data , error and completed , the data function executes when the Http call is successful here we are assigning returned data to the responseStatus object
Tthe error function executes when there is an error thrown from the Http call, the complete function executes when the Http call is completed here you can log a message that the request is completed

import { Component, OnInit,Input } from '@angular/core';
import { CommentService } from './app.comments.service'
import { Message } from './Message'
    selector: 'post-comment',
    templateUrl: 'posts.comment.html',
    providers: [CommentService]
export class CommentsComponent implements OnInit {
    constructor(private _commentService: CommentService) { }
    @Input() message:Message;
    responseStatus:Object= [];
    status:boolean ;
        console.log("submit Post click happend " +
           data => console.log(this.responseStatus = data),
           err => console.log(err),
           () => console.log('Request Completed')
        this.status = true;
    ngOnInit() {
       this.message = new Message(); = "keysandstokes";


The postComments method accepts Message that is passed down from the component when the click of post comment button, the Http calls returns observables in Angular 2 so we must import RXjs to operate them, the Http Post request takes two parameters post_url and Message object and returns response as JSON object,

import {HttpModule, Http,Response} from '@angular/http';
import {Injectable} from '@angular/core';
import 'rxjs/add/operator/map'
import { Message } from './Message'
export class CommentService {
    http: Http;
    returnCommentStatus:Object = [];
    posts_Url: string = '';
    constructor(public _http: Http) {
       this.http = _http;
    postComment(message:Message) {
       //ensure imports are included
        //import { Http, Response } from '@angular/http';
        //import 'rxjs/add/operator/map';
       return, message, {
       .map(res =>  res.json());

Go to the command prompt of the application folder and run the “npm start” to see comments component on the browser , the component renders like below, click of post submit button the status will be changed to congratulation message

By coderss

8 thought on “How to post data to the database using Angular 2 http post request”
  1. Hi Raj!
    Thank you for this tutorial , this is one of the best tutorial for newbie like me. I am starting learning on angular 2 specially on CRUD, i found that this tutorial is very helpful although i have some question but it’s perfectly awesome. I hope i can connect with you , you can reach me at skype: realtrue13
    Thank you!

  2. Hi raj, thank you for this great. if my getting the postid from the database, how can I proceed here.

    1. you need to pass post id to the message object, every post will have id, you need to get it pass it to the message object
      ngOnInit() {
      this.message = new Message(); = “keysandstokes”;

      1. thank you Raj, I am able to fix it. I was doing the same thing but was failing to call the correct variable. great article, I bookmarked your site

  3. Hi everybody, I hope you are doing good. Dear admin I had scroll down your site and found it really useful for web development tools. Since I am a developer, I most often refer people to use best website in the town for web development. Your efforts are really appreciable. We also provide web development tool. Here is the link

Leave a Reply

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