当我执行函数getLocalPosition()并在内部尝试设置位置类的变量时,收到下一个错误。
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;
}
}
谢谢你的时间
问题出在这一行
this.storage.get('position').then((val) => {
this.position = val;
}).catch((err) => {
console.log(err);
});
我用val设置了this.position,并且由于它不存在而无法访问方法setLat。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句