After running the getLocalPosition() function and attempting to set my Position class variable inside it, I encountered the following error.
TypeError: Cannot read property 'setLat' of null
at VM11086 main.js:52673
at t.invoke (VM11035 polyfills.js:3)
at Object.onInvoke (VM11086 main.js:34675)
at t.invoke (VM11035 polyfills.js:3)
at e.run (VM11035 polyfills.js:3)
at VM11035 polyfills.js:3
at t.invokeTask (VM11035 polyfills.js:3)
at Object.onInvokeTask (VM11086 main.js:34666)
at t.invokeTask (VM11035 polyfills.js:3)
at e.runTask (VM11035 polyfills.js:3)
VM11086 main.js:52685 TypeError: Cannot read property 'setLon' of null
at VM11086 main.js:52681
at t.invoke (VM11035 polyfills.js:3)
at Object.onInvoke (VM11086 main.js:34675)
at t.invoke (VM11035 polyfills.js:3)
at e.run (VM11035 polyfills.js:3)
at VM11035 polyfills.js:3
at t.invokeTask (VM11035 polyfills.js:3)
at Object.onInvokeTask (VM11086 main.js:34666)
at t.invokeTask (VM11035 polyfills.js:3)
at e.runTask (VM11035 polyfills.js:3)
However, setting the class in the constructor seems to work without any issues.
Here is the .ts code snippet:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Geolocation } from 'ionic-native';
import { Storage } from '@ionic/storage';
import { Position } from './clases';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
private position = new Position();
constructor(public navCtrl: NavController, public storage: Storage) {
this.position.setLat(1234311);
console.log(this.position);
// Or to get a key/value pair
this.storage.get('position').then((val) => {
this.position = val;
}).catch((err) => {
console.log(err);
});
}
getLocalPosition() {
Geolocation.getCurrentPosition().then((resp => {
try {
this.position.setLat(resp.coords.latitude);
} catch (e) {
if (e instanceof TypeError) {
console.log(e);
}
}
try {
this.position.setLon(resp.coords.longitude);
} catch (e) {
if (e instanceof TypeError) {
console.log(e);
}
}
//this.storage.set('position', this.position);
}))
}
}
And here is the class definition:
export class Position {
private lat: number;
private lon: number;
constructor(lat: number = 0, lon: number = 0) {
this.lat = lat;
this.lon = lon;
}
setLat(lat: number) {
this.lat = lat;
}
setLon(lon: number) {
this.lon = lon;
}
getLat() {
return this.lat;
}
getLon() {
return this.lon;
}
getPosition() {
let position = {
lat: this.lat,
lon: this.lon
}
return position;
}
}
Thank you for taking the time to review this.