无法访问全局模型 [英] Global Model Not Accesible

查看:40
本文介绍了无法访问全局模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 UI5 应用程序的 Component.js 中声明了一个模型,如下所示

I declared a model in Component.js of a UI5 application as below

init: function() {
  sap.ui.core.UIComponent.prototype.init.apply(this);
  var oModel1 = new sap.ui.model.json.JSONModel("model/mock.json");
  sap.ui.getCore().setModel(oModel1, "oModelForSales");
},

但无法在控制器内的任何 onInit 方法中访问模型,除非模型设置在视图上,如下所示:

but was not able to access the model in any of the onInit methods inside controllers unless the model is set on view instead as below:

var oModel1 = new sap.ui.model.json.JSONModel("model/routes.json");
this.getView().setModel(oModel1);

控制器 onInitsap.ui.getCore().getModel("oModelForSales") 的日志显示模型为 undefined 但我能够在 onBeforeRendering 处理程序中获取它.

The log for sap.ui.getCore().getModel("oModelForSales") in controllers onInit shows the model as undefined but I was able to fetch it in onBeforeRendering handler.

为什么在 Component.js 中设置的核心模型在 onInit 中无法访问?

Why are core models, set in Component.js, not accessible in onInit?

推荐答案

你能不能试试这个代码 -

can you once try this code -

init:function(){
        //sap.ui.core.UIComponent.prototype.init.apply(this);
        var oModel1 = new sap.ui.model.json.JSONModel("model/mock.json");
        sap.ui.getCore().setModel(oModel1,"oModelForSales");
        console.log(sap.ui.getCore().getModel("oModelForSales"));
        sap.ui.core.UIComponent.prototype.init.apply(this);
    },

然后在任何控制器的 init 方法中尝试 -

and then in you init method of any controller try -

console.log(sap.ui.getCore().getModel("oModelForSales"));

我认为 sap.ui.core.UIComponent.prototype.init.apply(this);-> 调用创建内容方法,并且您的视图和控制器甚至在您的模型定义之前就已初始化,因此您将未定义为模型.使用我的方法,我们先创建模型,然后调用 Component 中的 super init 方法.

I think sap.ui.core.UIComponent.prototype.init.apply(this);->calls the create content methods and your view and controllers are initialised even before your model is defined, hence you get undefined as model. Using my approach, we create the model first and then call the super init method in Component.

注意@Admins-> 我没有足够的点数来评论,所以添加一个答案.

Note @Admins-> I dont have enough points to comment, so adding an answer.

这篇关于无法访问全局模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆