How to wait for a JSONModel.loadData() request in UI5

Benvorth picture Benvorth · Jan 20, 2016 · Viewed 22.9k times · Source

In SAPUI5/OpenUI5, I have a JSONModel I populate by a file from server:

var oModel = new JSONModel();
oModel.loadData("http://127.0.0.1/data/config.json");
console.log(JSON.stringify(oModel.getData()));

The console logs undefined since the request is asynchronous. How to make it synchronous so console.log() is called after the data was loaded?

Answer

schnoedel picture schnoedel · Jan 21, 2016

Using synchronous ajax requests is not recommended as it blocks the UI and will probably result in a warning in the console.

You can attach to the Model.requestCompleted event to access the asynchronously loaded data:

oModel.attachRequestCompleted(function() {
        console.log(oModel.getData());
    });