如何获得manifest.json中定义的模型的长度?

时间:2017-03-22 21:00:00

标签: sapui5

我在manifest.json文件中定义了一个模型('products')。

的manifest.json

"dataSources": {
    "productsModel": {
        "type" : "JSON",
        "uri": "model/products.json"
    },

  ...

 "models": {
    "products": {
        "dataSource":  "productsModel"
        }

在我的控制器中,我想访问“产品”模型的长度。但我得到'未定义'。我觉得这应该相对简单,但我还没有找到直接答案。

main.controller.js

var mainController = BaseController.extend("vizConcept.controller.Main", {

        onInit: function(oEvent) {

          this.getView().setModel(this.getOwnerComponent().getModel("products"), "products");
            var oModel = this.getView().getModel("products");
            this.getView().setModel(oModel);

            //this logs as 'undefined'
            console.log(oModel.length);

products.json

{
    "products": [
        { 
            "Item": "1",
            "AwdDate": "20160715",
            "Hist": 171.9,
            "Current": 183

        },
        {
            "Item": "2",
            "AwdDate": "20160701",
            "Hist" : 144.3,
            "Current": 158.6
        },
        {
            "Item": "3",
            "AwdDate": "20150701",
            "Hist": 160,
            "Current": 165
        },
        { 
            "Item": "1",
            "AwdDate": "20160715",
            "Hist": 201,
            "Current": 167
        },
        {
             "Item": "2",
            "AwdDate": "20160801",
            "Hist" : 175.3,
            "Current": 178.2
        },
        {
            "Item": "3",
            "AwdDate": "20150721",
            "Hist": 160,
            "Current": 147
        },
        { 
            "Item": "1",
            "AwdDate": "20160715",
            "Hist": 175.9,
            "Current": 185.2
        },
        {
            "Item": "2",
            "AwdDate": "20161101",
            "Hist" : 165.3,
            "Current": 158.2
        },
        {
            "Item": "3",
            "AwdDate": "201700101",
            "Hist": 160,
            "Current": 165
        },
        {
            "Item": "4",
            "AwdDate": "201600401",
            "Hist": 173,
            "Current": 177
        }

    ]
}

1 个答案:

答案 0 :(得分:0)

我也使用本地JSON文件作为模型,并在清单文件中配置。但问题是我们会在 onInit 中获得模型,而不是数据。它将花费自己的甜蜜时间加载,然后它将添加数据。

如果您想在获取数据后执行任何操作,则意味着您必须在模型对象上附加事件 RequestCompleted ,如下所示。

onInit: function() {
    var model = this.getOwnerComponent().getModel("products");
    this.getView().setModel(model , "products");
    model.attachRequestCompleted(this._dataLoaded, this);
    model.attachRequestFailed(this._errorWhileDataLoading, this);
}

_dataLoaded: function(oEvent) {
    var model = this.getView().getModel("products");
    console.log(model.getData().length);
}

_errorWhileDataLoading: function(oEvent) {
    console.log("Error handling");
}

如果有任何错误,您可以从 RequestFailed 事件中获取错误。