Search code examples
odatasapui5odata-v4

SAPUI5 OData V4 Read


Can you please tell how to perform OData Read in OData V4 in SAPUI5 ?

I can do this very easily in OData V2, how do I achieve similar things with oData V4 ?

this_.getOwnerComponent().getModel("myModel").read("/zprojects", {
                "async": true,
                "success": function (oData) {
                    console.log(oData);
                },
                "error": function (oError) {
                    console.log(oError);
                }
            });

The problem for me is I want to massage the data to add additional values before I bind to view. Here is my complete code of oData V2:

this_.getOwnerComponent().getModel("myModel").read("/zprojects", {
                "async": true,
                "success": function (oData) {
                    var myArray = [];
                    var pos;

                    for (var i = 0; i < oData.results.length; i++) {
                        pos = myArray.map(function (e) {
                            return e.ID;
                        }).indexOf(oData.results[i].PROJECTID);
                        if (pos === -1) {
                            myArray.push({
                                ID: oData.results[i].PROJECTID,
                                PROJECT_DESC: oData.results[i].PROJECT_DESC
                            });
                        }
                    }
                    myArray.sort((a, b) => (a.PROJECT_DESC > b.PROJECT_DESC) ? 1 : -1);
                    myArray.unshift({
                        ID: "-1",
                        PROJECT_DESC: "Please select Project ID"
                    oModel = new sap.ui.model.json.JSONModel(myArray);
                    sap.ui.core.Fragment.byId("idFragment", "project").setModel(oModel);
                },
                "error": function (oError) {
                    console.log(oError);
                }
            });

Solution

  • From the documentation:

    The OData V4 model only supports data access using bindings. It does not provide any direct access to the data.

    You can get around that by creating fake bindings and listening to the dataReceived event, but I'd rather suggest using jQuery's ajax features to request the data, until the v4.ODataModel supports direct access to the data:

    $.get({
        url: "<your_service_url>/zprojects",
        success: function(data) {
            // your success logic
        },
        error: function(error) {
            // your error logic
        }
    });