Skip to Content
0

SAPUI5 - Retrieve OData model object from controllers onInit() function

Dec 13, 2016 at 12:06 PM

159

avatar image

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

I have googled the problem, and 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?

10 |10000 characters needed characters left characters exceeded
* Please Login or Register to Answer, Follow or Comment.

2 Answers

Sergio Guerrero Dec 14, 2016 at 03:28 PM
0

would it meet your requirement if you add it on the onBeforeRendering() event instead of the onInit() event?

your model will be ready from there onwards

Show 1 Share
10 |10000 characters needed characters left characters exceeded

The model is loaded when onBeforeRendering() runs and the property can be retrieved. The only problem is that this function is triggered on every screen change or even when a dialog appear, so it's not the best solution in my case. I need it to run once at startup.

0
Sergio Guerrero Dec 15, 2016 at 03:44 PM
0

I think the onBeforeRendering should only run the first time the view is loaded... otherwise, you can check if the model is instantiated or set a property after it is instantiated so you can skip the validation on subsequent runs ,... maybe this would work

Share
10 |10000 characters needed characters left characters exceeded