-1

I got the problem, that if I set a JSONModel in my controller, I am not able to get the data out of it:

var oModel = new JSONModel(jQuery.sap.getModulePath("QAQuickAccess", "/routes.json"));

this.getView().setModel(oModel);
console.log(oModel.getJSON());

The getJSON method just stringifies the oData object of the model. But it just gives me an empty object. If I only log oModel, I can see the object with its content:

Object content

honk
  • 9,137
  • 11
  • 75
  • 83

2 Answers2

0

You can access the properties via oModel.getProperty("/TileCollection");

Thomas L.
  • 249
  • 2
  • 15
  • My logs: oModel.getData() = { } oModel.getProperty("/TileCollection") = undefined oModel.getJSON() = { } oModel.oData = { } – Marvin Rügheimer Aug 17 '17 at 07:25
  • But in the same context your oModel log is filled with the data? – Thomas L. Aug 17 '17 at 07:28
  • The oData Object in oModel is filled with the "TileCollection".. The screen of it is above in the question. All logs are executed in the "onInit" function in the controller. – Marvin Rügheimer Aug 17 '17 at 07:31
  • There could be a problem with asynchronous loading of the JSON Model. Try this snippet after the instantiation of the JSON Model: `oModel.attachRequestCompleted(function() { console.log(oModel.getData()); });` – Thomas L. Aug 17 '17 at 07:34
0

There are 2 ways to achieve this:

1) Asynchronous way: By default the HTTP call that JSONModel makes is asynchronous. So if you want to access the Data after the HTTP request is completed then you need to use attachRequestCompleted method as mentioned in code snippet below. This will automatically call the listener after the HTTP request is completed and in the listener you can attach the JSONModel to your view or perform other businsess logic as mentioned below:

var oModel = new JSONModel(jQuery.sap.getModulePath("QAQuickAccess", "/routes.json"));
oModel.attachRequestCompleted(null,function() { 
console.log(oModel.getData()); 
this.getView().setModel(oModel) }, 
this);

2) Synchronous way: If you want the data to be loaded immediately then you can use the loadData method with below parameters. This will make the HTTP request synchronously:

var oModel = new JSONModel({});
var url = jQuery.sap.getModulePath("QAQuickAccess", "/routes.json")
oModel .loadData(url, "", false);
this.getView().setModel(oModel);
console.log(oModel .getData());