ERROR TypeError: Cannot set property 'items' of null
这是以下结果:
</ion-card>
<button ion-button round outline
(click)="logEvent($startTrackingButton)">Start tracking me</button>
<ion-card>
<ion-item>
<h2>Locations:</h2>
<ion-list no-lines>
<h3 ion-item *ngFor="let item of items" (click)="itemSelected(item)">
{{ item }}
</h3>
</ion-list>
</ion-item>
</ion-card>
</ion-content>
(在 Component.html 中),现在查看其 .ts 文件:
logEvent1(TrackNowButton) {
/*Initializing geolocation*/
// onSuccess Callback
// This method accepts a Position object,
// which contains the
// current GPS coordinates
var onSuccess = function(position) {
this.items = ([{
key: "1", value: {
Latitude: position.coords.latitude,
Longitude: position.coords.longitude
}
}, {
key: "2", value: {
Altitude: position.coords.altitude,
Accuracy: position.coords.accuracy
}
}, {
key: "3", value: {
Altitude_Accuracy: position.coords.altitudeAccuracy,
Heading: position.coords.heading
}
}, {
key: "4", value: {
Speed: position.coords.speed,
Timestamp: position.timestamp
}
}]);
};
// onError Callback receives a PositionError
// object
function onError(error) {
console.log('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
itemSelected(item: string) {
console.log("Selected Item", item);
}
我希望这是可读的...我不知道我在数据绑定(bind)方面做错了什么,因为我认为错误就在那里... 我还认为 .ts 文件中的部分有问题,我在其中写道: this.items= (...) 因为我认为该值不能绑定(bind)到 html 或其他内容。 我正在开发一个小程序,它经常跟踪运动并使用给定的参数记录它们。稍后我想添加 Mapbox 支持,但我需要先解决一些错误。
最佳答案
您收到的错误表明 this
为空。将分配给 onSuccess
的函数替换为箭头函数。它将使用 this
的正确值。
var onSuccess = (position: any) => {
this.items = ([{
key: "1", value: {
Latitude: position.coords.latitude,
Longitude: position.coords.longitude
}
}, {
key: "2", value: {
Altitude: position.coords.altitude,
Accuracy: position.coords.accuracy
}
}, {
key: "3", value: {
Altitude_Accuracy: position.coords.altitudeAccuracy,
Heading: position.coords.heading
}
}, {
key: "4", value: {
Speed: position.coords.speed,
Timestamp: position.timestamp
}
}]);
};
您可以使用JSON.stringify
将所选项目转换为字符串:
itemSelected(item: any) {
console.dir(item);
let str = JSON.stringify(item);
...
}
另一方面,如果需要将每个项目定义为字符串,您可以为数组中的每个项目调用 JSON.stringify
。
var onSuccess = (position: any) => {
this.items = ([JSON.stringify({
key: "1", value: {
Latitude: position.coords.latitude,
Longitude: position.coords.longitude
}
}), JSON.stringify({
key: "2", value: {
Altitude: position.coords.altitude,
Accuracy: position.coords.accuracy
}
}), JSON.stringify({
key: "3", value: {
Altitude_Accuracy: position.coords.altitudeAccuracy,
Heading: position.coords.heading
}
}), JSON.stringify({
key: "4", value: {
Speed: position.coords.speed,
Timestamp: position.timestamp
}
})]);
}
关于angular - Ionic 3 值绑定(bind)地理定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47838582/