sapui5

Global Model Not Accesible


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");
},

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);

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.

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


Solution

  • 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);
        },
    

    and then in you init method of any controller try -

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

    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.

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