SAPUI5:如果在 setModel 的同一函数中调用,则 getModel 返回 undefined [英] SAPUI5: getModel returns undefined if called within the same function of setModel

查看:69
本文介绍了SAPUI5:如果在 setModel 的同一函数中调用,则 getModel 返回 undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置模型并在按下某个按钮后从 OData 中检索它.

I'm trying to set a model and retrieving it from OData after pressing a certain button.

问题是当我在设置模型后立即调用 getModel 时,它返回 undefined.

The problem is when I call getModel right after setting the model, it returns undefined.

但是,如果我从另一个函数调用 getModel(在从其他函数测试模型之后),它会返回所需的输出.

However, if I call getModel from another function (after model being stetted from other functions), it returns the desired output.

参考代码:

onPressButton1: function(){
            var vEntityURL = "/CustomerSet(ID='000')";
            var sServiceUrl = "/Customers_SRV/";
            var oServiceModel = new sap.ui.model.odata.ODataModel(sServiceUrl, true);
            var oJsonModel = new sap.ui.model.json.JSONModel();

            oServiceModel.read(vEntityURL, {
                success: function(oData) {
                    oJsonModel.setData(oData);
                }
            });

            this.getView().setModel(oJsonModel, "Customers");

            var oCustomer = this.getView().getModel("Customers");
            console.log(oCustomer.getProperty("/Name"));
}

以上在控制台中返回 undefined.

The above returns undefined in the console.

但是,如果我按下另一个具有以下功能的按钮,它会起作用.

However, it works if I press another button with the following function.

onPressButton2: function(){
                var oCustomer = this.getView().getModel("Customers");
                console.log(oCustomer.getProperty("/Name"));
    }

推荐答案

这不是 sapui5 的问题,这是异步代码的常见行为:你可以确定只有在 读取方法.

This is not a sapui5 problem, it is the common behaviour of asynchronous code: you can be sure to have your data only in the success callback of the read method.

将最后三行代码移到成功函数中,你就完成了:-)

Move the last three lines of code inside the success function and you're done :-)

这篇关于SAPUI5:如果在 setModel 的同一函数中调用,则 getModel 返回 undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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