0

Can anyone tell how to access the oData Model(Manifest.json) inside the Init() of the Controller?

I tried to Access through Component.js. Tried Below Code in Component.js

var oModel = this.getModel("destinModel");
this.setModel(destinModel,"Model");

in Controller Init() Function--

var oComponent = this.getOwnerComponent();
var oModel = oComponent.getModel("Model");

This didn't work when I used it inside Init Function, but it worked inside onAfterRendering().

I need to access the Model Inside the Init() of the Controller.. if I can't please suggest me any alternative ways to access the Model..

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Navya
  • 1
  • 1
  • 1
  • `this.getOwnerComponent().getModel("Model")` has to work in `onInit` if the model was set on the Component. See https://stackoverflow.com/a/42251431/ – Boghyon Hoffmann May 01 '18 at 19:35

1 Answers1

1

I have also noticed that the model is being passed to the view only after the init function of your view has already been executed. But when the init function of your view is executed, the model does already exist in the component. So instead of this.getModel(), you could use this.getComponent().getModel() to access it. E.g.:

onInit: function() {
    this.component = this.getComponent();
    this.model = this.component.getModel("destinModel");
    this.setModel(this.model, "Model");
},

To be able to actually access the model from your init function (if you plan to do so), you will have to wait until the model's metadata has been loaded. To run code as soon as the metadata has been loaded, the ODataModel provides the metadataLoaded function. This function returns a promise to which you can hook up your functionality. E.g.:

onInit: function() {
    this.component = this.getComponent();
    this.model = this.component.getModel("destinModel");
    this.setModel(this.model, "Model");
    this.model.metadataLoaded().then(function() {
        alert("We have the model to our disposal at this point");
    }.bind(this));
},
jpenninkhof
  • 1,920
  • 1
  • 11
  • 12
  • Hi JP... Here am Not Binding my view to Model Directly... in Init Function am Loading the Model after Processing am binding the Processed model to View.. Till now i was Using Hard coded URL.. Now tried to Use through the Component... But the Problems am Facing are 1. When i Load the Model in The Init using GetComponent its returning undefined 2. when i load the Model in the Function onAfter Rendering its Returning the Model But No odata in it. – Navya Sep 25 '16 at 03:31
  • So have you tried `this.getComponent().getModel("destinModel")` from the onInit of your controller as mentioned in the answer? That shouldn't be undefined. – jpenninkhof Sep 25 '16 at 10:52
  • `this.getOwnerComponent().getModel()` will work in the onInit hook if you're controller/view are bootstrapped with the application – Kyle Jul 07 '17 at 19:08