视图模型中的JSON值仅显示为[对象对象]

时间:2017-12-01 01:15:02

标签: nativescript

这将是一个菜鸟问题。我正在开发我的第一个NativeScript应用程序,一个简单的GPS跟踪器。这只是一个观点。我得到了Location插件,它可以很好地将位置数据输出到控制台。它似乎也更新了View Model。但是当我尝试将它绑定到Label元素的文本时,它只显示[object Object],无论我做什么。

视图模型:

var observableModule = require("data/observable");

function viewModel() {

    return new observableModule.fromObject({
        "locations": [],
        "lastLocation": {
            "latitude": "0",
            "longitude": "0",
            "altitude": 0,
            "horizontalAccuracy": 0,
            "verticalAccuracy": 0,
            "speed": "0",
            "direction": "0",
            "timestamp": new Date().toISOString()
        },
        "lastUpload": "Unknown"
    });

}


module.exports = viewModel;

视图XML:(只是重要部分)

<Label text="Current location:"/>
<Label text="{{ lastLocation?.latitude }} ; {{ lastLocation?.longitude }}" />

<Label text="Last location update:"/>
<Label text="{{ lastLocation?.timestamp }}" />

<Label text="Last successful upload:"/>
<Label text="{{ lastUpload }}" />

代码:

var frameModule = require("ui/frame");
var viewModel = require("./home-view-model");
var geolocation = require("nativescript-geolocation");
var dialog = require("ui/dialogs");

var viewModel = new viewModel();

function onLoaded(args) {

    page = args.object;
    page.bindingContext = viewModel;

    var enableLocation = new Promise((resolve, reject) => {
        geolocation.enableLocationRequest(true)
            .then(
            success => resolve(),
            error => reject(error)
            )
    })

        .then(
        () => {
            watchId = geolocation.watchLocation(
                function (loc) {
                    if (loc) {
                        viewModel.lastLocation = loc;
                        console.log(viewModel.lastLocation.latitude + ' ; ' + viewModel.lastLocation.longitude);
                    }
                },
                function (e) {
                    dialogsModule.alert('Location error: ' + e.message);
                },
                {
                    desiredAccuracy: 3,
                    updateDistance: 0,
                    minimumUpdateTime: 10000
                })
        },

        error => {
            dialogsModule.alert('Location error: ' + e.message);
        }
        )

}

exports.onLoaded = onLoaded;

console.log行正确显示纬度和经度值。视图显示[object Object],但它显示lastUpload值。我在视图中做错了什么?

1 个答案:

答案 0 :(得分:0)

哦,是的,这是一个菜鸟问题。解决方案是我不应该在模板中使用问号。

<Label text="Current location:"/>
<Label text="{{ lastLocation.latitude }} ; {{ lastLocation.longitude }}" />

<Label text="Last location update:"/>
<Label text="{{ lastLocation.timestamp }}" />

现在可行。