2016-08-19 7 views
0

Я пытаюсь выполнить приложение с Ionic2 с вопросами об импорте из файла JSON и отображать их в тесте. Мне удалось успешно импортировать все вопросы в массив из объектов uniqueChoiceQuestion. Однако, когда я пытаюсь построить массив `questionList ', значения, которые я вставляю в него, исчезают, когда я пытаюсь использовать его в другой функции.Угловой 2 + Ионный 2: объекты нажимают на массив, но он пуст, когда я пытаюсь его использовать.

Моего test.ts

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 init, 
    the questions array will be initialised, 
    the questions will be loaded on 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)); 

    } 
//Here, 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 files 
    */ 
    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); 
//That will generate 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 Я попытался debbuging программы больше и теперь я считаю, что проблема в том, что this.loadFirstQuestion() в настоящее время выполняется перед this.loadQuestions() (на ngOnInit)

ответ

0

Загрузка вопросов asynchronous. Поэтому он начинается с выполнения вызова async, не дожидаясь его завершения, затем переходит к выполнению loadFirstQuestion. Здесь вы не получите список вопросов, потому что он еще не загружен. Вы можете попробовать позвонить loadfirstquestion в подписке.

.subscribe(
    this.processQuestionsData.bind(this), 
    error => console.log("Test - loadQuestions() - Error: ", error), 
()=>this.loadFirstQuestion(); 
); 
Смежные вопросы