In my Ionic2 application, I am working on importing questions from a JSON file and displaying them in a test. I have successfully imported all the questions into an array of 'uniqueChoiceQuestion' objects. However, I am facing an issue where the values I push into the 'questionList' array disappear when I try to use it in another function.
Here is a snippet of my test.ts file:
import {Component, OnInit, Input} from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';
/*----- Question Classes -----*/
import {UniqueChoiceQuestion} from './../../classes/questions/uniqueChoiceQuestion/uniqueChoiceQuestion';
//Has id: number, content: string, options: Array<any>
import {QuestionList} from './../../classes/questions/questionList/questionList'
//Has id: number; type: string;
import {GetList} from './../../services/getList/getList';
@Component({
templateUrl: 'build/pages/test/test.html',
providers: [GetList]
})
export class TestPage implements OnInit {
/*----- Questions array -----*/
public questionsUnique: Array<UniqueChoiceQuestion>;
public questionList: Array<QuestionList>;
public firstQuestion: any;
constructor(private navController: NavController, private getList: GetList) {
}
/* On page initialization,
the questions array will be initialized,
the questions will be loaded into the arrays
*/
ngOnInit() {
this.setupArrays();
this.loadQuestions();
this.loadFirstQuestion();
}
/* Initializes the questions arrays as empty
*/
setupArrays() {
this.questionsUnique = [];
this.questionList = [];
}
/* Load the JSON data into the correct type of array
*/
processQuestionsData(data) {
for (let i = 0; i < data.length; i++) {
let question = data[i];
this["questions" + question.type].push(question);
this["setUpQuestion" + question.type](this["questions" + question.type].length - 1);
this.questionList.push(new QuestionList(question.id, question.type));
}
//The array is printed correctly with all the questions ids and types
console.log(this.questionList);
}
/* Load data into a UniqueChoiceQuestion array
*/
setUpQuestionUnique(arrayId) {
let container = this.questionsUnique[arrayId];
container.viewConstruct = new UniqueChoiceQuestion(
container.id,
container.content,
container.options
);
}
/* Loads questions from a JSON file
*/
loadQuestions() {
this.getList.load()
.subscribe(
this.processQuestionsData.bind(this),
error => console.log("Test - loadQuestions() - Error: ", error)
);
}
loadFirstQuestion() {
//However, when I try to print the array here, it is empty
console.log(this.questionList);
//This generates a 'TypeError: Cannot read property 'type' of undefined' error
let firstQuestion = this["questions" + this.questionList[0].type][this.questionList[0].id];
this["setUpQuestion" + this.questionList[0].type](this.questionList[0].id);
console.log(this.firstQuestion);
}
UPDATE Upon further debugging, it seems that the issue might be that this.loadFirstQuestion() is being executed before this.loadQuestions() in the ngOnInit function.