如何在UI5应用中用oModel.read读取单条数据并存储到变量
Fixing OData Read Issue for Single Record in UI5
Hey there, let's work through your problem with reading a single OData record and storing it in a variable. First, let's break down the issues in your code:
Key Issues in Your Current Code
Invalid OData Path Syntax:
Your path/Komm(ZSMATERIALTEXT ='"+text123+")has two critical syntax errors:- You're missing a closing single quote after
text123 - The correct OData key syntax doesn't include a space between the key name and the equals sign
It should strictly follow the format:/EntitySet(KeyName='KeyValue')
- You're missing a closing single quote after
Uninitialized Variable:
Yourtext123variable is declared but has no assigned value—this will result in an empty key parameter, which the OData service will definitely reject.Missing Result Storage Logic:
You haven't added code to save the returnedoDatainto your target variable (oroJsonModel) within the success callback.
Corrected Code Example
Here's the fixed version with clear explanations:
var hostPort = ""; // Ensure this is set correctly if your service uses a different host/port var oDataPath = "/.../KOMMI_SERVICE/"; var sServiceUrl = hostPort + oDataPath; // Note: For UI5 versions >= 1.30, use sap.ui.model.odata.v2.ODataModel instead (older ODataModel is deprecated) var oModel = new sap.ui.model.odata.ODataModel(sServiceUrl, true); var oJsonModel = new sap.ui.model.json.JSONModel(); var targetRecord; // This variable will hold your fetched single record var text123 = "your-actual-material-text"; // Replace with the real value you want to query oModel.read( "/Komm(ZSMATERIALTEXT='" + text123 + "')", // Fixed path syntax { success: function(oData, oResponse) { targetRecord = oData; // Store the single record in your variable oJsonModel.setData(oData); // Optional: Load data into JSONModel for UI binding console.log("Fetched data successfully:", oData); }, error: function(err) { console.error("Error fetching data:", err); } } );
Additional Tips
- Use ES6 Template Literals for Readability: Replace string concatenation with template literals to make the path easier to write and debug:
`/Komm(ZSMATERIALTEXT='${text123}')` - Verify Service Metadata: Always check your OData service's metadata (accessible at
sServiceUrl/$metadata) to confirm the exact entity set name and key property names—this avoids typos that break your requests. - Upgrade to Modern OData Models: If you're using a recent UI5 version, switch to
sap.ui.model.odata.v2.ODataModel(orODataV4Modelfor OData V4 services) as the legacyODataModelis no longer actively maintained.
内容的提问来源于stack exchange,提问作者Eimerman
相关产品推荐
相关产品推荐

