Submitting Data in Ionic 3 using Http Post and Storing in Sqlite with Angular 4

I am facing an issue while trying to post an array of contacts on a WebService.

When I send the array, the data appears as NULL in the WebService response.

I am confused about how to use Let params{}

The error message shows "object undefined".

Additionally, the POST method is not functioning properly.

My technology stack includes Ionic3 - Angular4 and Sqlite.

Here's a snippet from my home.ts file:

public contactos: any [] = [];

constructor(public navCtrl: NavController,
    private sqlite: SQLite,
    private toast: Toast,
    public http: Http) {
    }
        postRequest(){
                this.sqlite.create({
                name: 'ionicdb.db',
                location: 'default'
            }).then((db: SQLiteObject) =>{
              db.executeSql('SELECT * FROM Contactos ORDER BY rowid DESC', {})
              .then(result =>  {
                this.contactos = [];
                for(var i=0; i<result.rows.length; i++) {
                  this.contactos.push({
                    rowid:result.rows.item(i).rowid,
                    nombre:result.rows.item(i).nombre,
                    telefono:result.rows.item(i).telefono,
                    ext:result.rows.item(i).ext,
                    correo:result.rows.item(i).correo,
                    empresa:result.rows.item(i).empresa})  

                    var headers = new Headers();
                    headers.append("Accept", 'application/json');
                    headers.append('Content-Type', 'application/x-www-form-urlencoded');
                    let options = new RequestOptions({ headers: headers });
                    let params = { 
                      nombre: 'Sergio',
                      telefono: '1234567',
                      ext: '000',
                      correo: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b011e091c12141f101a16... // abbreviated for brevity
                }

                 this.http.post("http://181.48.244.108/FeriaDutotec/api/Contactos1", JSON.stringify(params), options)
                .subscribe(contactos => {
                this.contactos.push(contactos.json())
                console.log(contactos ['_body']);
                this.toast.show('Datos Sincronizados!' , '4000', 'center').subscribe(
                  toast => {
                    console.log(contactos);
                  }
                )
                }, error => {
                console.log(error.message);// Error obteniendo los datos!
                this.toast.show('Error en la sincronizacion!'+ error.message, '4000' , 'center').subscribe( // abbreviated for brevity
                  )
                  }); 
    }  
        console.log('Result')
        })
        .catch(e => console.log(e));
        console.log('Create')
        }) 
        .catch(e => console.log(e));
        }

Answer №1

Kindly update this line

this.http.post("http://181.48.244.108/FeriaDutotec/api/Contactos1", JSON.stringify(this.contactos), options)

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

Setting a TypeScript collection field within an object prior to sending an HTTP POST request

Encountered an issue while attempting to POST an Object (User). The error message appeared when structuring it as follows: Below is the model class used: export class User { userRoles: Set<UserRole>; id: number; } In my TypeScript file, I included ...

The setter function for a component is being triggered twice when utilizing the slice method with @Input in Angular 4

Using two-way data binding in Angular 4 to pass an array to another component can be done like this: component.ts import {Component} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component. ...

Running into issues compiling Ionic 4 with Angular 7 inside a Docker container

Facing Issues Compiling Ionic 4 with Angular 7 in Docker I am trying to compile a project using Ionic 4 and Angular 7 within Docker. Here are the steps I have taken: I manually created an image with Java JDK version 8, following this article How To Ins ...

Tips for implementing a real-time search feature in Angular

I require assistance. I am attempting to perform a live search using the following code: when text is entered into an input, I want my targetListOptions array, which is used in a select dropdown, to update accordingly. The code runs without errors, but not ...

The type 'ElementClass' is lacking several key properties, specifically context, setState, forceUpdate, props, and refs

I'm currently developing a web application using NextJS with Typescript. During my testing phase with Jest+Enzyme, I encountered the following error message: ** Test suite failed to run TypeScript diagnostics (customize using `[jest-config].globals. ...

Guide to linking two input fields using a single datepicker

To achieve the goal of filling two input fields simultaneously, take a look at the following code snippet: <mat-form-field> <input matInput [matDatepicker]="startDate" formControlName="SaleDate" /> ...

How can you inform TypeScript about a file that will be included using a script tag?

I am currently utilizing TypeScript for my front-end JavaScript development, and I have a situation where I am loading two scripts from my index.html file as shown below: <script src="replacements.js"></script> <script src="socket.js">&l ...

Receiving an eslint error while trying to integrate Stripe pricing table into a React web application

If you're looking to incorporate a Stripe documentation code snippet for adding a stripe-pricing-table element, here's what they suggest: import * as React from 'react'; // If you're using TypeScript, don't forget to include ...

Leverage both props and destructuring in your Typescript + React projects for maximum efficiency!

Is it possible to use both destructuring and props in React? For instance, can I have specific inputs like name and age that are directly accessed through destructuring, while also accessing additional inputs via props? Example The desired outcome would ...

Is it possible to leverage ES6 modules within a Node.js application while also debugging it using Visual Studio?

Trying to create a basic node.js module test project using ES6 in Visual Studio 2015 has resulted in build errors, preventing me from running or debugging the application. Could it be that I arrived at the party too soon? I attempted opening and building ...

I have noticed that my unit test case does not include coverage for the if statement

Here is the function I have in my TypeScript file: routeToIndividualPortal(sessionToken: string) { let redirectUrl = this.relayState; console.log("Pre-source-check Indivual URL : " + redirectUrl); let url = ""; if(redirectUrl.includes(this. ...

Router navigation does not trigger LifeCycle calls

I currently have the following routes set up: {path:'home', component:HomeComponent, canActivate: [AuthGuard]}, {path:'profile', component:UserProfileComponent, canActivate: [AuthGuard] }, Additionally, in my navbar.component, I hav ...

Angular Universal - Transfer state does not populate correctly when the URL contains unsafe characters, leading to duplicate XHR calls

Working with Angular(12) and Angular Universal has presented me with a challenge regarding the transfer state between the server and client side. On the client side, I am using the TransferHttpCacheModule, while on the server side module, I have implemente ...

What is the solution for resolving the error message "Property '' does not exist on type 'typeof import'"?

Hi everyone, I'm a new Angular developer who is working on implementing authentication. I recently added the auth0-angular package to my project and now I'm encountering an error when creating a WebAuth() instance in my code editor (VS Code). Th ...

Create an HTML button on the homepage that directs users to the "about" page

I've been struggling to make a button in my Ionic app navigate to a different page upon clicking. Despite being new to Ionic, I've spent hours trying to solve this issue. Below is the HTML code in home.page.html: <ion-header> &l ...

The issue with the React Hook for window resize not updating remains unresolved

I have a React Hook designed to update the window size on resize, but it's not functioning correctly. Can someone please help explain why this is happening and provide guidance on how to utilize this hook in another component to create a Boolean value ...

The process of extracting values from an HTML tag using Angular interpolation

I am working on an Angular application that has the following code structure: <p>{{item.content}}</p> The content displayed includes text mixed with an <a> tag containing various attributes like this: <p>You can find the content ...

How come the inference mechanism selects the type from the last function in the intersection of functions?

type T = (() => 1) & (() => 2) extends () => infer R ? R : unknown What is the reason that T is not never (1 & 2)? Does the type always come from the last function, or can it come from one of them? ...

Mapping through multiple items in a loop using Javascript

Typescript also functions Consider an array structured like this const elementList = ['one', 'two', 'three', 'four', 'five'] Now, suppose I want to generate components that appear as follows <div&g ...

Customizing the MUI Select component with TypeScript

What seems to be the issue in this code snippet? TS2322: Type '(event: SelectChangeEvent) => void' is not assignable to type '(event: SelectChangeEvent<unknown>, child: ReactNode) => void'.   Types of parameters 'even ...