The oModel.loadData
will asynchronously request data.
The callback you passed to attachRequestCompleted
will be called once the request has finished (execution will not block at loadData()
until the data is available)
when your console.log(datelist, datelist.length);
line runs, datelist
will still be an empty array.
The reason you can see the items in the array in your browser console is that the request already completed when you inspected it.
You can try the following in your browser console:
var arr = [];
console.log(arr, arr.length); // [], 0
arr.push(1); arr.push(2); arr.push(3);
// console.log(arr, arr.length); // [1,2,3], 3
The first log will output the array and when you inspect it the items will be there - they just weren't there yet when you accessed .length
.
To fix this you could keep datelist
inside the request completed handler:
var oModel = new sap.ui.model.json.JSONModel();
oModel.attachRequestCompleted(function() {
var oFeiertageBerlin = oModel.getData().BE;
var datelist = [];
for (var prop in oFeiertageBerlin) {
datelist.push(oFeiertageBerlin[prop].datum);
}
console.log(datelist, datelist.length);
// do something with the datelist here
});
var jDatum = new Date();
var jLink = "https://feiertage-api.de/api/?jahr=" + jDatum.getFullYear();
oModel.loadData(jLink);
With sapui you can return the array as a json model, to which you can then bind in your views:
function loadHolidays() {
var result = new sap.ui.model.json.JSONModel({datelist: []});
var oModel = new sap.ui.model.json.JSONModel();
oModel.attachRequestCompleted(function() {
var oFeiertageBerlin = oModel.getData().BE;
var datelist = [];
for (var prop in oFeiertageBerlin) {
datelist.push(oFeiertageBerlin[prop].datum);
}
result.setData({datelist: datelist});
});
var jDatum = new Date();
var jLink = "https://feiertage-api.de/api/?jahr=" + jDatum.getFullYear();
oModel.loadData(jLink);
return result;
}
var model = loadHolidays();
// attach model to view
// e.g. sap.ui.getCore().setModel(model);
Plunker Example with the dates displayed in a table: Plunker Holiday Example