zyrex zyrex - 6 months ago 470
JSON Question

SAPUI5 get single property from JSON-Model

I am currently trying to figure out how I can retrieve a single value from a sap.ui.model.json.JSONModel

in my main view:

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

var getConfigCallback = function(config) {
gConfigModel.setData(config);
};

oController.getConfiguration(getConfigCallback);
console.log(gConfigModel);


in my controller:

getConfiguration : function(callback) {

var sServiceUrl = "/sap/opu/odata/sap/xxx/ConfigurationSet('Initialize')";

var config = {};
callback(config);

$.getJSON(sServiceUrl).done(function(data) {
config = data.d;
callback(config);
});
},


In my console.log statement I can see that the data was successfully passed from the backend and successfully set to the JSON model. My requirement is to store the value of attribute Editable in a single variable.

console.log-statement

I already tried gConfigModel.getProperty('/'), didnt work. tried to access gConfigModel.oData was undefined .. How can I store it in a single value?

Solution Comment: If you catch data from a backend, you have to take care how long it takes. data can be available later then expected, in my case I added 1s timeout, afterwards I can access the property easily

setTimeout(function() {
console.log(gConfigModel.getProperty('/Editable'));
}, 1000);

Answer

<script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-theme="sap_bluecrystal" data-sap-ui-libs="sap.m"></script>

<script>
    function getConfiguration(callback) {

        var sServiceUrl = "/sap/opu/odata/sap/xxx/ConfigurationSet('Initialize')";

        var config = {};

        var data = {
            "d": {
                "_metadata": "",
                "Backup01": "01",
                "Editable": "True"
            }
        };

        setTimeout((function() {
            config = data;
            callback(config);
        })(), 2000);
    };
    var gConfigModel = new sap.ui.model.json.JSONModel();

    var getConfigCallback = function(config) {
        gConfigModel.setData(config);
        alert(gConfigModel.getProperty("/d/Editable"));
    };

    getConfiguration(getConfigCallback);
</script>