SAPUI5新手求助:加载Manifest中JSON模型时出现getModel未定义错误
Hey there! Let's break down why you're seeing that error and get your app working properly.
错误原因分析
The TypeError: Cannot read property ‘getModel’ of undefined happens because this.getOwnerComponent() is returning undefined in your View1 controller. This is because you're not loading your app through the ComponentContainer in your index.html—instead, you're directly creating the View and adding it to an App control. Without the Component context, the View can't access the Component and its models defined in the manifest.
分步修复方案
1. 修复index.html:使用ComponentContainer加载应用
Replace your current sap.ui.getCore().attachInit callback with this code to properly initialize your component:
<script> sap.ui.getCore().attachInit(function() { new sap.m.Shell({ app: new sap.ui.core.ComponentContainer({ height : "100%", name : "com.newproject.firstsapui5project" }) }).placeAt("content"); }); </script>
This ensures your component is loaded correctly, and all models defined in the manifest are available to your views.
2. 简化View1.controller.js(可选但推荐)
Since you've already defined the simpleForm model in your manifest, the View will automatically inherit this model from the Component. You don't need to manually set it again unless you want to rename it. If you keep the current code, it will still work once the Component is properly loaded, but you can simplify it to:
sap.ui.define([ "sap/ui/core/mvc/Controller" ], function (Controller) { "use strict"; var oController= Controller.extend("com.newproject.firstsapui5project.controller.View1", { onInit: function () { // Optional: If you want to use "DataModel" as the model name in your view var dataModel = this.getOwnerComponent().getModel("simpleForm"); this.getView().setModel(dataModel, "DataModel"); } }); return oController; });
3. 修复View1.view.xml中的绑定错误
You have a typo in your first Input binding—you forgot the curly braces. Also, adjust the binding path to match your model name (either simpleForm or DataModel):
<f:SimpleForm id="idSimpleForm" editable="true" layout="ResponsiveGridLayout" title='TEST Form'> <f:content> <Label text="First Name"/> <!-- Fix: Add curly braces --> <Input value="{simpleForm>/Form/0/first}" /> <Label text="Last Name"/> <Input value="{simpleForm>/Form/0/lastname}"></Input> </f:content> </f:SimpleForm>
If you chose to use DataModel in the controller, change the bindings to {DataModel>/Form/0/first} instead.
4. 验证路由配置(可选)
Your routing config looks okay, but since you're using a single view right now, it will work once the component is loaded. When you add navigation later, make sure to use this.getOwnerComponent().getRouter() to access the router.
测试运行
After making these changes, reload your app. The error should be gone, and your Simple Form should display the data from data.json correctly.
内容的提问来源于stack exchange,提问作者Parag Nandy

