Ionic/Angular How to Make HTTP Calls with Demo API


Today, we'll learn more about HTTP requests and how to structure our app using providers. In this Ionic 5/Angular tutorial, we'll learn how to send an example HTTP post request to a server (or post data to a server) and how to get data from a server API. Most of the time, the user fills out a form to send the POST data. We'll send a simple JSON object in this example.

For a quick look, you can use the commands below to make a new, blank Ionic Project:

ionic start <name> blank --type=angular --spec false

Ionic 4 Steps
Step 1 — The first step is to make an Ionic 4 app.

Step 2 — Using HttpClientModule for making http calls.

Step 3 — Using HttpClient for sending http requests.

Step 4 — Using demo API and getting & posting data.

Step 5 — To test an app, you can run it on a browser, Android, or iOS.

** — Let's Start - Ionic/Angular HTTP CALLS Example

Now go to src/app/app.module.ts and then you need to import HttpClientModule  and declare it in the imports section like the following code:

... // Other Imports
import { HttpClientModule } from '@angular/common/http';

@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,
   HttpClientModule
  ],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
bootstrap: [AppComponent]
})
export class AppModule {}


Once this is done. We are ready to go ahead.


Adding a button in Ionic Application to send post requests

Next, open the src\app\home\home.page.html file & then update this file by adding a button which will be used to call the method to send the post request:

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic 5/Angular POST Request Example
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <p>
      Sending a POST Request Demo with Ionic/Angular Application
  </p>
   <button ion-button (click)="sendPostRequest()">Post Data</button>
</ion-content>

Sending Post Requests with Ionic 5 HttpClient

Next, open the src/app/home/home.page.ts file and update the code with the following changes:

import { Component } from '@angular/core';
import { Headers, HttpClient , RequestOptions } from '@angular/common/http';
 
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(private httpClient: HttpClient) {
  }

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

    let postData = {
            name: "Customer0000",
            email: "customer0000@email.com",
            tel: "0000111122"
    }

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

First, we bring import in the classes Headers, HttpClient, & RequestOptions. After that, we use httpClient to add the HttpClient service to the page constructor.

Next, we set up the sendPostRequest() method, which will be called when clicking the button. We are reaching the post() method on the HttpClient service instance given to us. The API endpoint is the first parameter, and the customer data object is the second. We also use the.subscribe() method to subscribe to the observable that the post() method gives us. If the operation works, we show the _body of the data that the success function sent us. If something goes wrong, we write about it on the console.

Adding a button in Ionic 5 to fetch dummy data from API

Start by opening the src\app\home\home.page.html file and update it by adding a button which will be used to call the method to get the data from API:


<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic 5/Angular Get Request Example
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <p>
     POST Request Demo in Ionic/Angular
  </p>
   <button ion-button (click)="getData()">Get Data</button>
</ion-content>

Getting Data from API with Ionic 5 HttpClient

After this, Go to the home page and open src\app\home\home.page.ts componenet file. Replace the file code with the following changes:

import { Component, OnInit } from '@angular/core';
import { HttpClient, Headers, RequestOptions } from '@angular/common/http';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {

  constructor(public httpClient: HttpClient) {
  }
  ngOnInit(){}

  getData() {
this.httpClient.get("https://jsonplaceholder.typicode.com/todos/")
.subscribe(data => { console.log(data); }, error => { console.log(error); }); } }

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

Next, we define the getData() method which will be called when the button is clicked. We are calling the get() method from the injected instance of the HttpClient service. The API endpoint is the first parameter, and the customer data object is the second. We also subscribe to the observable returned by the get() method using the .subscribe() method. If the operation is successful we display the _body of data received by the success function. If error occurs or something fails then we log the error on the console and it will help us debug the code.

Conclusion

If you have any question, let me know in the comments below and I will try to best to help you!

Tags

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !