How to get the JSONModel property in my controller?

I need to restore the property of my JSONModel in my controller. The scenario is as follows:

I have a "questionnaire" model (questionnaire.json) that contains questions and answers. Then I have a controller (App.controller.js). In this controller, I created another model in onInit called "currentQuestion", because I need to implement a script in which the next question should be loaded when the user clicks on the next button. I am trying to get a property of my "questionnaire" model, but I encountered an error:

Unable to read getProperty property from undefined.

Here you can see the model data and my controller:

questionnaire.json

{
    "data": [{
        "question": "Which pet do you like from the following?",
        "answers": ["Cats", "Rabbits", "Dogs", "Hamsters"],
        "correct": 1
    }, {
        "question": "Which pet do you prefer from the following?",
        "answers": ["Cats", "Dogs"],
        "correct": 1
    }, {
        "question": "What food brand does your pet eat?",
        "answers": ["Pedigree", "Catfood", "Rabbitfood", "HamstersFood"],
        "correct": 1
    }]
}

App.controller.js

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/ui/model/json/JSONModel"
], function(Controller, JSONModel){

    Controller.extend("opensap.onlinequestionnaire.controller.App", {
        onInit: function() {
            this.questionSetUp();
            this.getView().setModel(new JSONModel({
                    index: false,
                    question: {}
            }), "currentQuestion");

            var oCurrentQuestionModel = this.getView().getModel("currentQuestion");
            var oQuestionModel = this.getView().getModel("questionnaire");
            var iCurrentIndex = oCurrentQuestionModel.getProperty("/index");
            var oQuestion = oQuestionModel.getProperty("/data/0/question");
            console.log(oQuestion);
            console.log(iCurrentIndex);
            iCurrentIndex = iCurrentIndex ? ++iCurrentIndex : 0;
            console.log(iCurrentIndex);
        }
    });
});

oQuestion, . 0- ?

+1
3

, , init

, . , undefined . , . , (manifest.json) . , view.getModel , . : -, , , , , onInit , , . view.getParent onInit null. , "" . , onInit : this.getOwnerComponent().getModel("modelName")

getProperty undefined

.

+1

setModel (oModel, sName?) . "currentQuestion" , questionnaire.json. oCurrentQuestionModel. , : oCurrentQuestionModel.getProperty("/data/0/question"); , oQuestionModel.

0

In your case. I think you should change

var oQuestionModel = this.getView().getModel("questionnaire");

to

var oQuestionModel = this.getView().getModel();

because you did not name your model so that it becomes the default model.

0
source

Source: https://habr.com/ru/post/1667709/


All Articles