You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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')
  • Uninitialized Variable:
    Your text123 variable 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 returned oData into your target variable (or oJsonModel) 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 (or ODataV4Model for OData V4 services) as the legacy ODataModel is no longer actively maintained.

内容的提问来源于stack exchange,提问作者Eimerman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:18:11