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.