How to post data to the database using Angular 2 http post request

In this article, I am going to explain to you how to post data using angular 2 Http Post request ,  the example which I have taken out here is submit a comment to the article, for this, I am building separate comments component using JSON placeholder fake rest API, this API takes JSON Object as an input parameter something like below

Building comments component

posts.comment.html

The first thing which I am going to do out here is to design and build an input form for comment’s, this angular 2 component allows to end user to enter name, email and 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

Message.ts

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

app.posts.submit.component.ts

Now build a angular2 component for comments and it should be implemented ngOnInit method, in this method, I have created a new Message object, the name and postId of message object 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 can assign to the responseStatus object and the 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

app.comments.service.ts

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,

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

comments

Comments

  1. By Johnrel

    Reply

Leave a Reply

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