当我执行函数getLocalPosition()时,我尝试设置类Position的变量,我收到下一个错误。
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)
但是如果我在构造函数中设置我的类工作正常。
这是我的.ts
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);
}))
}
}

在这里我的班级
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;
}
}

感谢您的时间
答案 0 :(得分:0)
问题在于这一行
this.storage.get('position').then((val) => {
this.position = val;
}).catch((err) => {
console.log(err);
});
我用val设置this.position,之后无法访问setLat方法,因为它不存在。