Search code examples
odatasapui5

ODataModel passing "expand" parameter in read


I'd like to pass expand parameters to read because it doesn't work if I call the service like this:

oModel1.read("/LinesSet?$expand=ToCells", {

Solution

  • The read API awaits a map of options as a second argument in which we can define any query using the property urlParameters:

    oModel1.read("/LinesSet", {
      urlParameters: {
        "$expand": "ToCells",
        "$select": "LineID,ToCells/CellID,...", // reduce data load
      },
      filters: [ // Filter required from sap/ui/model/Filter
        new Filter({/*...*/}), // reduce data load
      ],
      success: this.onSuccess.bind(this),
      // ...
    });
    

    ⚠️ Please note that loading large amounts of data significantly affects memory consumption and UX negatively. This might even lead to crashing the application altogether ultimately. See the section Loading Large Amounts of Data from the documentation.

    Whenever you use methods like [...] sap.ui.model.odata.v2.ODataModel#read [...] in application code, your application must not load large amounts of data.

    ⚠️ read is a low-level API from the application's point of view. There are other APIs and approaches that can help reducing the amount controller code.


    Alternative (better) solution

    I'd like to emphasize that v2.ODataModel#read is often not required. You can simply make use of the OData Context/ListBinding by assigning the corresponding name of the <NavigationProperty> to the control in XML:

    <Table binding="{ToThatRelatedSingleEntity}" items="{ToThatRelatedCollection}" growing="true">

    (You might have to add templateShareable to the aggregation binding as explained in Lifecycle of Binding Templates)

    The binding, not the application, will then prepare a request automatically for you. No need to use an intermediate JSONModel. Same with v4.ODataModel which doesn't even have the read method. This makes also migrating to OData V4 much easier.

    Documentation: OData V2 Model1


    1: If the documentation is unclear or missing something, create an issue in https://github.com/SAP/openui5-docs/issues.