0

How to write the http module function to read data from local json file? I am now using this to read the data. I want the function to read the data from this url - http://localhost:8000/app/source.json

var observableModule = require("data/observable");
var source = require("./source.json");
var properties = require("./properties.json");

function HomeViewModel() {
 var viewModel = new observableModule.Observable();

 viewModel.set("categoricalSource", source.categoricalSource);
 viewModel.set("categoryProperty", properties.categoryProperty);
 viewModel.set("valueProperty", properties.valueProperty);
 return viewModel;
}

module.exports = HomeViewModel;
LSA
  • 33
  • 5

1 Answers1

2

To access localhost from the Android emulator, refer to Accessing localhost:port from Android emulator

In short - http://10.0.2.2:<hostport> replaces localhost:<hostport>

Refer to the NativeScript docs on http for making http requests. To access http://localhost:8000/app/source.json yours should look like so:

http.getJSON("http://10.0.2.2:8000/source.json").then(function (r) {
    //// Argument (r) is JSON!
}, function (e) {
    //// Argument (e) is Error!
    //console.log(e);
});

And finally, if you need to read a JSON from the application directory, a require should suffice.

pkanev
  • 1,486
  • 1
  • 12
  • 20
  • Alright! So is this how you write it - viewModel.set("categoricalSource", source.categoricalSource); - in the space where it says //Argument (r) is JSON! – LSA Jan 17 '18 at 08:55