Ionic 3 Http Post by Example

In this Ionic 3 tutorial, we'll learn how to send an example HTTP post request to a server (or post data to a server). Usually the post data is submitted from a form by the user.

In the previous tutorial, we've seen what's a REST API and RxJS. We also configured our Ionic 3 application to use HttpClient and created (mocked) a REST server for testing. Now let's see how to send a POST request to our server.

Start by opening the src\pages\home\home.html file then update it by adding a button which will be used to call the method to send the post request:

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic 3 Post Request Example
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <p>
      Sending a POST Request Example
  </p>
   <button ion-button (click)="sendPostRequest()">Post Data</button>
</ion-content>

Next, open the src\page\home\home.ts file and add the following changes:

import { Component } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/common/http';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public navCtrl: NavController, public httpClient: HttpClient) {
  }

  sendPostRequest() {
    var headers = new Headers();
    headers.append("Accept", 'application/json');
    headers.append('Content-Type', 'application/json' );
    const requestOptions = new RequestOptions({ headers: headers });

    let postData = {
            "name": "Customer004",
            "email": "customer004@email.com",
            "tel": "0000252525"
    }

    this.http.post("http://127.0.0.1:3000/customers", postData, requestOptions)
      .subscribe(data => {
        console.log(data['_body']);
       }, error => {
        console.log(error);
      });
  }
}

We start by importing the HttpClient, Headers, RequestOptions classes. After that, we inject the HttpClient service into the component constructor as httpclient.

Next, we define the sendPostRequest() method which will be called when the button is clicked. We are calling the post() method from the injected instance of the HttpClient service. The first parameter is the API endpoint and the second parameter is the customer data object. We also subscribe to the observable returned by the post() method using the .subscribe() method. If the operation is successful we display the _body of data received by the success function. If there is an error we log the error on the console.

Conclusion

In this quick tutorial, we've seen to use the HttpClient service to send http POST data in Ionic 3 applications.


comments powered by Disqus