issue with sending http requests using ionic2/3

I'm still relatively new to using ionic2, even though I have some experience with programming in general. Currently, I'm experimenting with ionic2 and attempting to send simple get/post requests to my locally hosted web services for development purposes, but for some reason, the services are not being called.

Interestingly, there are no errors or warnings generated when I make these get and post calls.


import { Injectable, NgZone } from '@angular/core';

import { BackgroundGeolocation } from '@ionic-native/background-geolocation';

import { Geolocation, Geoposition } from '@ionic-native/geolocation';

import { Http, Response, Headers, RequestOptions } from '@angular/http';

import { Observable } from 'rxjs';

import 'rxjs/add/operator/map';

import 'rxjs/add/operator/catch';

import 'rxjs/add/operator/toPromise';import 'rxjs/add/operator/filter';

@Injectable()
export class LocationTracker {
    public watch: any;
    public lat: number = 0;
    public lng: number = 0;
    public http: Http;

    constructor(public zone: NgZone, public backgroundGeolocation: BackgroundGeolocation,
        public geolocation: Geolocation, http: Http) {
            this.http = http;
    }

    public postLocationData(lat: number, lng: number)  {
        var JSONObject = {"latitude": "" + lat, "longitude": "" + lng };

        console.log("Posting: " + JSON.stringify(JSONObject));
        let headerOptions: any = { 'Content-Type': 'application/json' };
        let headers = new Headers(headerOptions);

        // The simple get service. Curl from command line works
        this.http.get("http://192.168.1.2:8080/location/new1/")
        .map((response: Response) => {
            console.log('Response is: ' + response);
        })
        .catch((this.handleErrorObservable));

        // The simple post service. Curl from command line works. Note that in the service, the post param is captured as a String (Java) and then I am casting the string to an Object using Gson
        this.http.post("http://192.168.1.2:8080/location/new/", JSON.stringify(JSONObject), new RequestOptions({ headers: headers }))
        .map((response: Response) => {
            console.log('Response is: ' + response);
        })
        .catch((this.handleErrorObservable));
    }

    startTracking() {
        // lat and lng are populated here
    }

    stopTracking() {
        // something ...
    }
    private handleErrorObservable (error: Response | any) {
        console.error('Error in handleErrorObservable: ' + ( error.message || error ) );
        return Observable.throw(error.message || error);
    }
}

A similar code snippet can also be found on a pastebin which I posted (https://pastebin.com/f39vW1hD). Any assistance or advice would be greatly appreciated.

Answer №1

Not utilizing the subscribe or async pipe will result in not being able to view the sent requests.

function sendLocationData(latitude: number, longitude: number)  {
    var locationObject = {"latitude": "" + latitude, "longitude": "" + longitude };

    console.log("Sending: " + JSON.stringify(locationObject));
    let headerOptions: any = { 'Content-Type': 'application/json' };
    let headers = new Headers(headerOptions);

    // Simple get service. Command line Curl works fine
    this.http.get("http://192.168.1.2:8080/location/new1/")
    .map((response: Response) => {
        console.log('Received response: ' + response);
    })
    .subscribe(data => console.log(data));

    // Simple post service. Command line Curl works fine. Note that the post parameter is handled as a String (Java), then converted to an Object using Gson
    this.http.post("http://192.168.1.2:8080/location/new/", JSON.stringify(locationObject), new RequestOptions({ headers: headers }))
    .map((response: Response) => {
        console.log('Received response: ' + response);
    })
    .subscribe(data => console.log(data));
}

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

Step-by-step guide for building and populating a JavaScript Dictionary

Does anyone know how to create a Dictionary with a key and a list of values pair in Python? I have been able to create dictionaries with a single value for each key, but now I need to store multiple items as values for each key. Here is what I have tried: ...

What is the best way to spin a div HTML layer?

I'm trying to modify a Div layer that looks like this: ... <style type="text/css"> <!-- #newImg { position:absolute; left:180px; top:99px; width:704px; height:387px; z-index:1; background-image:url(../Pictures/rep ...

FireFox is unresponsive to OPTIONS requests

I have a webpage that is accessed through HTTP. The client-side code is making AJAX requests for authorization to the same domain, but using HTTPS, which causes CORS issues. When using FireFox, the request looks like this: // domains and cookies are chang ...

Guide to developing a manual tally counter with recorded logs using HTML and JavaScript

I am currently in need of assistance with creating a manual input counter using the App Script Editor. My website design already includes a single input textbox, a reset button, and a disabled box. What I would like to achieve is that when I enter a numb ...

Is it true that TypeScript prohibits the presence of circular references under the condition of having generic parameters

I encountered an issue of type error in the given code snippet Type alias 'bar2' circularly references itself.ts(2456) type foo = { bars: bar[]; }; //works fine type bar = foo; type foo2<T extends Record<string, unknown> = Record< ...

What is the best way to restrict event handling to only occur once every X seconds using jQuery or JavaScript?

Is there a way to limit handling the event of a rapidly-firing keypress to once per X seconds using jQuery or vanilla JavaScript? Check out this jsfiddle that demonstrates rapid keypress firing without any limiting on the handling: View here ...

The p5js function pixelDensity() does not provide improved resolution on retina screens

Currently, I am working on a project that involves generating collages from sets of photos. This process includes averaging the pixels' colors of the images and then using that averaged color to plot points on the canvas. However, when I zoom in on re ...

What could be the reason why I am unable to choose my radio button? What error am I

The output can be found here... I am struggling to use a radio button and cannot seem to select it. Can someone please explain what issue I am facing? Any help would be greatly appreciated. const [value, setValue] = React.useState({ yes:"", no:"" ...

Using 'expect', 'toBe', and 'toEqual' in Angular 2 - A step-by-step guide!

Looking to implement something I came across that resembles this: let item1 = {value:5}; let item2 = {value:5}; // Should result in true. expect(item1).toEqual(item2); Unfortunately, an error is being thrown: EXCEPTION: Error in :0:0 caused by: expect ...

What's the trick to aligning the label on the material-ui text field to the right side?

I am working on a React project with an RTL layout using material-ui and typescript. I am struggling to align the label of a text field to the right. Can anyone help me with this? https://i.sstatic.net/UrkIF.jpg ...

Is there a quick way to use AJAX in Rails?

By using the remote:true attribute on a form and responding from the controller with :js, Rails is instructed to run a specific javascript file. For instance, when deleting a user, you would have the User controller with the Destroy action. Then, you woul ...

Leveraging periods within a MySQL database: Node.js for seamless updates

I am currently facing a challenge in updating a column name that contains a period in node using node-mysql. I appreciate the convenience of being able to update multiple columns by providing an object with keys, but the string escaping process with node-m ...

Utilize VueJS to pass back iteration values using a custom node extension

Hey there! I'm currently working on a Vue app that generates a color palette based on a key color. The palette consists of 2 lighter shades and 2 darker shades of the key color. To achieve this, I have set up an input field where users can enter a hex ...

On mobile devices, the height of the absolutely positioned element is larger than its

I currently have an element with a background image that includes an absolutely positioned element at the bottom. As the screen width decreases, the height of the absolutely positioned element increases and surpasses the parent element. Since absolutely p ...

Chart.js malfunctioning - Uncaught reference error:

In an attempt to visualize time series data using chart.js, I am encountering some issues. The data is extracted from a psql database, converted to JSON format, and then passed as a parameter to a JavaScript function for rendering the chart. Although the ...

retrieving data from identical identifiers within a loop

Within my while loop, I am retrieving various dates for each event. <?php while( have_rows('_event_date_time_slots') ): the_row(); ?> <div> <h3 class="date-<?php echo $post->ID?>" name="tttdate<?php e ...

Interactive search tool for toggling visibility of elements

Hello everyone, this is my initial post on StackOverflow. Keeping my fingers crossed that it goes smoothly! <input type="Text" id="filterTextBox" placeholder="Filter by name"/> <script type="text/javascript" src="/resources/events.js"></scr ...

Emulate clicking a radio button (using PHP and JS)

For the past week, I've been struggling to solve this issue with no luck. I admit that I am new to this area, so I ask for your patience. My current problem involves using TastyIgniter, an online food ordering system. In order to add items to the car ...

Issues within jQuery internal workings, implementing improved exception handling for fn.bind/fn.apply on draggable elements

I've been experimenting with wrapping JavaScript try/catch blocks as demonstrated on this link. It functions properly, essentially encapsulating code in a try/catch block to handle errors like so: $.handleErrors(function(e){ console.log("an erro ...

Jquery ajax is failing to achieve success, but it is important not to trigger an error

My jQuery ajax request seems to be stuck in limbo - it's not throwing an error, but it also never reaches the success function. This is how my code looks: function delete() { $("input[name='delete[]']:checked").each(function() { ...