如何在 onInit 上获取模型? [英] How to get model on onInit?

查看:67
本文介绍了如何在 onInit 上获取模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

manifest.json 中,我有以下模型定义:

In manifest.json, I have following model definition:

{
    "sap.ui5": {
        "models": {
            "SalesInvoices": {
                "type": "sap.ui.model.odata.v2.ODataModel",
                "settings": {
                    "defaultOperationMode": "Server",
                    "defaultCountMode": "Request"
                },
                "dataSource": "ZAM_SALES_STATISTICS_CDS",
                "preload": true
            }
        }
    }
}

如您所见,SalesInvoices 已连接到 OData 服务.

As you can see, SalesInvoices is connected to the OData service.

现在在控制器中的 onInit 函数上,我试图从 OData 获取 Metadata 如下:

Now on the onInit function in the controller, I am trying to get Metadata from OData as following:

{ // Controller
    onInit: function() {
        const oPayerModel = this.getView().getModel("SalesInvoices");
        console.log(oPayerModel.getMetadata());
        setTimeout(() => {
            const oPayerModel = this.getView().getModel("SalesInvoices");
            console.log(oPayerModel.getMetadata());
        }, 600);
    },
    // ...
}

如您所见,我不得不延迟获取 OData 实例.
setTimeout 不推荐在 SAPUI5 中使用,我怎样才能做得更好?

As you can see, I have to delay to get the OData instance.
setTimeout is not recommended to use in SAPUI5, how can I do it better?

推荐答案

你可以避免 setTimeout,如 在这个答案中提到,通过使用 API metadataLoaded 而不是它返回一个承诺.成功加载服务元数据后,即会履行承诺.

You can avoid setTimeout, as mentioned in this answer, by using the API metadataLoaded instead which returns a promise. The promise is fulfilled once the service metadata is loaded successfully.

onInit: async function() {
  const oPayerModel = this.getOwnerComponent().getModel("SalesInvoices");
  await oPayerModel.metadataLoaded();
  const serviceMetadata = oPayerModel.getServiceMetadata(); // NOT .getMetadata()
  // ...
},


关于在 onInit 中未定义模型,以下是更好解释的答案:


About the model being undefined in onInit, here are answers with better explanations:

这篇关于如何在 onInit 上获取模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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