Nativescript将获取响应数据传递到关卡文本 [英] Nativescript pass fetch response data to a level text
本文介绍了Nativescript将获取响应数据传递到关卡文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的nativescript应用中,我试图通过fetch模块从API的响应中建立一个层次.但是我不知道如何在Obserable中绑定上下文.如何在页面加载时绑定上下文.我的代码-
In my nativescript app,I am trying to bulid a level from the response of my API through fetch module.But I don't know how to bind the context in obserable.How to bind the context when page loaded.Here is my code-
我的api响应-
[{"value":"12000$"}]
我想从我的关卡文本中的 {{price}} 中的响应中获取该值.
I want to get that value from response in {{price}} in my level text.
查看文件-
<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);
});
推荐答案
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中使用已加载的事件
and in your page.xml use the loaded event
<Page loaded="onLoaded">
<Label text="{{ ip }}"/>
</page>
在这种情况下,httpbin.org以格式返回数据
In this case, httpbin.org is returning the data in format
{"origin" : "some-ip-address-here"}
这篇关于Nativescript将获取响应数据传递到关卡文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文