Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 293
Benvorth Avatar asked Jan 20 '16 14:01

Benvorth


4 Answers

Since UI5 version 1.64.0, the API loadData returns a Promise instance:

logLoadedData: async function () {
  const jsonModel = new JSONModel();
  await jsonModel.loadData("<host>/data/config.json");
  console.log(jsonModel.getData()); // after the loadData promise is resolved
},

Alternatively, there is also the API dataLoaded which returns a promise as well. It will resolve when all requests sent by loadData are finished. Here is a syntax without async-await:

doSomethingWith: async function (jsonModel) {
  // Not sure if the model has all data loaded? Just use dataLoaded:
  await jsonModel.dataLoaded();
  console.log(jsonModel.getData());
},

The API loadData is also called internally when the constructor function of JSONModel was called with a string (URL) as an argument. In that case, dataLoaded might come in handy as well.

like image 101
Boghyon Hoffmann Avatar answered Nov 15 '22 17:11

Boghyon Hoffmann


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());
    });
like image 25
schnoedel Avatar answered Nov 15 '22 17:11

schnoedel


The keyword you are looking for is "Deferred"-object --> it enables you to wait for an AJAX request in SAPUI5.

Check this for SAPUI5 context: SAPUI5 Wait for an Deferred-Object // wait for .done() function

like image 36
dotchuZ Avatar answered Nov 15 '22 19:11

dotchuZ


You can use the attachRequestCompleted-listener from the Model [1]

model.attachRequestCompleted(function(){
    console.log(this.getData()); //"this" is the model
});

Another function to use is

$.get(url, function(response){
    console.log(response);
    model.setData(response);
});
// or
$.ajax(url, {
    success: function(){
        console.log(response);
        model.setData(response);
    }
});

This has the advantage that you can configure the request with every setting that jQuery.ajax accepts [2]

like image 34
herrlock Avatar answered Nov 15 '22 19:11

herrlock