cancel
Showing results for 
Search instead for 
Did you mean: 

JSONModel getProperty() fails

stefan_heitzer
Participant
0 Kudos
431

Hi,

I have the following code:

var oModel = new sap.ui.model.json.JSONModel();

oModel.loadData("credentials.json");

var user = oModel.getProperty("/credentials/benutzer");

And the following JSON file:

{

    "credentials": {

        "benutzer": "test",

        "passwort": "test"

    }

}

When I say now alert(user) I always get "undefined" ...

Does anybody now why it doesn't work?

Greetings

Stef

Accepted Solutions (0)

Answers (4)

Answers (4)

0 Kudos

I am facing the similar issue some one please help me with the issue in my code.

Model File:

sap.ui.define([

], function () { 'use strict'; return { createJSONModel: function (sPath) { var oModel = new sap.ui.model.json.JSONModel(); oModel.loadData(sPath); return oModel; } }
});

Controller File: onFlip() function

onFlip: function () { var oModel1 = oModels.createJSONModel('model/mockdata/mydata.json'); var oEmpStr1 = oModel1.getProperty('/empstr');
if (oEmpStr1.empId == 1009) { sap.ui.getCore().setModel(oModel2, 'json2'); } else { sap.ui.getCore().setModel(oModel1, 'json2'); }
}


The var oEmpStr1 = oModel1.getProperty('/empstr'); is giving undefined

david_bizer
Product and Topic Expert
Product and Topic Expert
0 Kudos

loadData() returns a promise. You can get that promise and wait for it to be resolved/rejected. As Brian mentioned, loadData can take some time and the getProperty gets called before the model is loaded.

May you try this await syntax or just use standard promise then/catch handling:

createJSONModel: async function (sPath) { 
var oModel = new sap.ui.model.json.JSONModel(); 
try{
var res = await oModel.loadData(sPath); // await the promise to be finished
return oModel;
}
catch (e){
// error handling if data loading failed with return
}
} 
<br>
stefan_heitzer
Participant
0 Kudos

Hi,

it works fine with the .attachRequestCompleted Event. But now comes another question. Am I able to update the json source file? I only have one entry in it:

{

    "credentials": {

        "user": "test",

        "password": "test"

    }

}

and now I want to set user and password to the value which the user enters. Is this possible?

Looking forward to your answers

Greetings and thanks!

Stef

Former Member
0 Kudos

Hi Stefan,

please also refer to answer here: http://scn.sap.com/thread/3438779

Regards

Stefan

brian_keenan
Product and Topic Expert
Product and Topic Expert
0 Kudos

this could be a matter of "timing". When calling the "loadData" method, you trigger an async request. This means, that when you try to get a property from the model there is no guarantee that the data is loaded already. You might consider registering an event handler on the "RequestCompleted" event of the model. Please refer to the API reference for more details.