Nativescript将获取响应数据传递给级别文本

时间:2016-10-25 08:27:06

标签: android post httpresponse nativescript

在我的nativescript应用程序中,我试图通过fetch模块从我的API的响应中提升一个级别。但是我不知道如何在obserable中绑定上下文。如何在页面加载时绑定上下文。这是我的代码 -

来自我api的回复 -

[{"value":"12000$"}]

我希望在我的关卡文字中 {{price}} 的回复中获得

查看文件 -

 <Page loaded="loaded">
    <GridLayout>
     <Label text="{{ price }}"  horizontalAlignment="left" verticalAlignment="center" tap="model" />
        </GridLayout>
</Page>

获取请求 -

fetch("http://10.0.2.2:8000/get_model", {
         method: "POST",
        headers: { "Content-Type": "application/json" },

       body: JSON.stringify({
                 brand: data,
    })  
 }).then(r => { return r.json(); }).then(function (data) {  
 console.log(data[0].value);

 //How to push the value in obserable?

 }, function (e) {
     console.log("Error occurred " + e);
});

1 个答案:

答案 0 :(得分:0)

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

var viewModel = new observableModule.Observable();
viewModel.set("ip", "none"); // initial value

function onLoaded(args) {
   var page = args.object;
   page.bindingContext = viewModel;

   fetch("http://httpbin.org/ip", {
        method: "GET",
        headers: { "Content-Type": "application/json" }
    })
    .then(function (res) { return res.json(); })
    .then(function (data) {  
        console.log(data.origin); // make sure you are getting the value 
        viewModel.set("ip", data.origin); // binding to "price"

    })
}
exports.onLoaded = onLoaded;

并在page.xml中使用加载的事件

<Page loaded="onLoaded">
    <Label text="{{ ip }}"/>
</page>

在这种情况下,httpbin.org以格式

返回数据
{"origin" : "some-ip-address-here"}