Challenges associated with implementing HTTP in Ionic version 3

I've been working on developing an app using Ionic 3 and I decided to implement the HTTP module. For reference, I relied on the official documentation provided by the Ionic framework.

Documentation Link: https://ionicframework.com/docs/native/http/

To begin, I executed the following commands:

$ ionic cordova plugin add cordova-plugin-advanced-http
$ npm install --save @ionic-native/http

Progressing smoothly, I then integrated this module into my app.module.ts file, resulting in the following code:

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';    
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ResultstatsPage } from '../pages/resultstats/resultstats';
import { HTTP } from '@ionic-native/http';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ResultstatsPage
  ],
  imports: [
    BrowserModule,   
    IonicModule.forRoot(MyApp),
    HTTP    
  ],
  bootstrap: [IonicApp],
...  

In order to interact with the server using the HTTP module, I created a function like this:

getStats(){
   this.http.get(this.url, {}, this.apikey)
  .then(data => {

    console.log(data.status);
    console.log(data.data); // data received by server
    console.log(data.headers);

  })
  ...
  });
}

However, when I attempt to run the application using 'ionic serve', I encounter an error message as shown in the screenshot below:

https://i.sstatic.net/fQJLv.png

Despite trying out various solutions, I have not been able to resolve this issue. Any guidance or suggestions on how to address this problem would be greatly appreciated.

Answer №1

Based on the information provided at https://ionicframework.com/docs/native/http/, it is advised not to import

import { HTTP } from '@ionic-native/http';
in the app.module.ts file, but rather in the component or service responsible for making the API call.

In Angular, the equivalent approach would involve three different files. In the app.module.ts file:

import {HttpClientModule} from '@angular/common/http';
...
providers: [
    HttpClientModule,
    ...

Then, in the api.service.ts file:

import {HttpClient, HttpErrorResponse, HttpHeaders, HttpParams, HttpResponse} from '@angular/common/http';
...
getItems(): any{
  const apiURL = `${this.API_URL}/items`;
  this.items =
   this._http
    .get(apiURL)
    .catch(this.handleError);
  return this.items;
}

handleError(error: HttpErrorResponse) {
  console.log('An HTTP GET error occurred.');
  console.error(error);
  let errorMessage;
  if (error.error instanceof Error) {
    errorMessage = `An error occurred: ${error.error.message}`;
  } else {
    errorMessage = `Server returned code: ${error.status}, error message is: ${error.message}`;
  }
  console.error(errorMessage);
  return errorMessage;
}

Lastly, in the my.component.that.calls.api file:

this.apiservice.getItems().subscribe(returnData => {
  if(returnData !== null && returnData !== undefined && returnData.length > 1){
    // Perform actions with returnData 
    console.log(returnData);
  }
}, (error) => console.log(error), () => {});

Answer №2

Consider using the HttpModule for imports:

imports: [
    BrowserModule,   
    IonicModule.forRoot(MyApp),
    HttpModule    
  ],

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to display complete content of Ionic 3 webpage

Trying to print a specific part of an Ionic page which contains a long list of items. However, encountering an issue where the entire list doesn't fit on one page and requires scrolling down to view all items. Expecting the print dialog, triggered by ...

Struggling to get bcrypt.ts to install on Visual Studio Code for password hashing purposes

As part of my current project, I am working on creating a hash function following the guidelines provided by npmjs's bcrypt documentation: var bcrypt = require('bcrypt.ts'); // Synchronous - 10 rounds equal 10 hashes/sec const saltRounds = ...

What is the best way to kickstart a Reactive Angular 2 form by utilizing an Observable?

My current strategy involves storing the form values in my ngrx store so that users can easily navigate around the site and return to the form if needed. The concept is to have the form values repopulate from the store using an observable. This is how I a ...

Angular: verifying the presence of any of the ng-content slots supplied

I have a component template that contains several ng-content elements: <div class="form__general"> <ng-content select="[general]"></ng-content> </div> <div class="form__footer"> <ng-conte ...

How come the variable `T` has been assigned two distinct types?

Consider the following code snippet: function test<T extends unknown[]>(source: [...T], b: T) { return b; } const arg = [1, 'hello', { a: 1 }] const res = test(arg, []) const res1 = test([1, 'hello', { a: 1 }], []) The variabl ...

Using React with Typescript: Passing Props and Defining Data Types

As a relatively new TypeScript enthusiast, I find myself facing some challenges. Specifically, I am struggling with errors in my code and uncertain about how to properly pass props and select the correct type. Any guidance on this matter would be greatly a ...

The TypeScript compiler is unable to locate the module react-scripts within the lerna webpack configuration

Recently, I've been working on setting up a new project using lerna, react-scripts, webpack, and sass. Here is my current directory structure: myApp /packages /myReactApp -> a react create app application /tsconfig.json /package ...

The BarcodeScanner feature in Ionic is currently not functioning properly on iOS devices

I have developed an Ionic app that works perfectly on Android devices. However, I am facing issues with the barcode scanner not functioning correctly on iOS. Here is my code snippet: $cordovaBarcodeScanner.scan().then(function (barcodeData) { console.l ...

The concept of inheriting directives/scopes

Just wondering if directives declared within a Component in Angular 2 automatically apply to its children Components. And when it comes to variables declared on the Component, do they get inherited by the children Components or must they be explicitly pa ...

Issue TS2339: The object does not have a property named 'includes'

There seems to be an issue that I am encountering: error TS2339: Property 'includes' does not exist on type '{}'. This error occurs when attempting to verify if a username is available or not. Interestingly, the functionality works ...

Mapping Interface Types in Typescript

I am currently exploring the correct method to map Interface record value types to the appropriate function type. function stringCompose(): string { return '' } function numberCompose(): number { return 0 } interface Demo { stringVal ...

Having trouble with launching angular2-webpack-start?

I am currently working through a tutorial on GitHub that can be found at: https://github.com/AngularClass/angular2-webpack-starter/ After installing node+npm and running npm install, I cloned the git repository, ran npm install, but encountered an error m ...

The data in the object bound to [ngmodel] does not update properly when changed within a method

Hello everyone, I am in need of some assistance with a puzzling issue. Currently, I am generating a set of inputs using JSON. When I make changes to the data in the web interface, everything works fine. The problem arises when I try to modify the value ...

Tips for incorporating Google Docs into a web application to enable previewing, editing, and saving functionality

Incorporating Google Docs into a web application (Angular 10) for previewing, editing, and saving is my goal. I have documents stored on my server and would like to utilize Google Docs to preview these files, whether they are stored on Amazon S3, Azure, o ...

Adding custom TypeScript classes to an Electron project is a straightforward process that allows developers to enhance their

Currently working on a hello world project in Electron and stumbled across the possibility of using Typescript for the Main process, . The provided instructions suggest changing the file extension from index.js to index.ts and updating the package.json fi ...

What is the process for converting/executing TypeScript into JavaScript?

Having trouble running https://github.com/airgram/airgram Encountering this warning message from the post (node:9374) Warning: To load an ES module, set "type": "module" Have already added {"type": "module"} To pa ...

Dragula drag and drop in a single direction with Angular 2 copy functionality

Attempting to utilize ng2 dragula for one-way drag and drop with copy functionality. Below is the template I am working with: `<div> <div class='wrapper'> <div class='container' id='no-drop' [dragula]=& ...

Tips for applying personalized CSS to individual Toast notifications in Angular

MY QUESTION : I am looking to customize the CSS of a single toast used in Angular components. While there may be multiple toasts, I specifically want to style one particular toast differently. For example, the toast image can be viewed here: example toast ...

What is preventing Apollo from achieving full transformation?

I have been struggling with an issue involving Apollo mutation for the past 2 days. Whenever I call a mutation on Angular Apollo generated code and subscribe to it, the subscription never completes. I am expecting a result from the server, but nothing is ...

Compiling errors arise due to TypeScript 2.4 Generic Inference

Experiencing issues with existing TypeScript code breaking due to changes in generic inference. For instance: interface Task { num: number; } interface MyTask extends Task { description: string; } interface Job {} type Executor<J> = <T ...