0
votes

I'm trying to retrieve an OData model from inside onInit function from a controller in SAPUI5 for storing a property into a local variable. I have tried the following without success:

var oModel = this.getView().getModel();   // returns undefined
var oModel = sap.ui.getCore().getModel(); // returns undefined

It it seems like the model is not yet set when the onInit is running. Because of this, I have tried:

var oModel = this.getOwnerComponent().getModel(); // returns empty odata object
var value = oModel.getProperty("/Collection/Property"); // returns undefined

The exact same code works just fine in all other functions except onInit, but I need it inside this function.

How can I retrieve the model and property in onInit?

1
In my work examples I use this.getModel("ModelName"); and it works fine. Have you tried to maybe name your model before trying to get it? - wdoering
Yes, I have tried naming the model. Does not make any difference. Are you calling the model from inside onInit ? - Chessinio
About models being undefined: stackoverflow.com/a/42251431/5846045 About retrieving OData: stackoverflow.com/a/46662969/5846045 Pretty much what matbtt's answer already mentioned. I'd suggest to accept his answer to inform others that this question got solved. - Boghyon Hoffmann

1 Answers

0
votes

This works as expected. Please check the documentation about application initialization.

I assume that this is related to the way model propagation is working. A model instantiated by the component is propagated to its views unless the specific view has a model with the same name. Normally you instantiate view specific models in onInit, i.e. the runtime knows all view specific models only after onInit has been performed.

Normally you should be able to get the component models in onInit via:

this.getOwnerComponent().getModel()

Update: As far as I know getProperty does not trigger a read automatically. Thus you have to to do it own your own (documentation):

this.getOwnerComponent().getModel().read(path, paramaters);

With parameters you pass a success handler where you can access the required values.