问题
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-
Response from my api-
[{"value":"12000$"}]
I want to get that value from response in {{price}} in my level text.
view file-
<Page loaded="loaded">
<GridLayout>
<Label text="{{ price }}" horizontalAlignment="left" verticalAlignment="center" tap="model" />
</GridLayout>
</Page>
Fetch request-
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:
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;
and in your page.xml use the loaded event
<Page loaded="onLoaded">
<Label text="{{ ip }}"/>
</page>
In this case, httpbin.org is returning the data in format
{"origin" : "some-ip-address-here"}
来源:https://stackoverflow.com/questions/40234986/nativescript-pass-fetch-response-data-to-a-level-text