简体   繁体   English

Angular 2 + Ionic 2:对象推送到数组,但是当我尝试使用它时它为空

[英]Angular 2 + Ionic 2: objects push to array, but it is empty when I try to use it

I'm trying to do an application with Ionic2 with imports questions from a JSON file and display them in a test. 我正在尝试使用Ionic2做一个具有从JSON文件导入问题的应用程序,并在测试中显示它们。 I was able to successfully import all the questions in the array made of 'uniqueChoiceQuestion' objects. 我能够成功地将所有问题导入由“ uniqueChoiceQuestion”对象组成的数组中。 However, when I try to construct the 'questionList' array, the values I pushed into it disappear when I try to use it in another function. 但是,当我尝试构造'questionList'数组时,当我尝试在另一个函数中使用它时,推入其中的值就会消失。

My 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 I tried debbuging the program more and now I believe the problem is that this.loadFirstQuestion() is being executed before this.loadQuestions() (on ngOnInit) UPDATE我尝试对程序进行更多调试,现在我相信问题是在this.loadQuestions()之前(在ngOnInit上)正在执行this.loadFirstQuestion()

Load questions is asynchronous . 加载问题是asynchronous So it starts by executing the async call, doesnt wait for it to complete, then goes to execute loadFirstQuestion . 因此,它从执行async调用开始,不等待它完成,然后执行loadFirstQuestion Here you don't get the question list because it isn't loaded yet. 在这里您没有得到问题列表,因为它尚未加载。 You can try calling loadfirstquestion in subscribe. 您可以尝试在订阅中调用loadfirstquestion

.subscribe(
  this.processQuestionsData.bind(this),
  error => console.log("Test - loadQuestions() - Error: ", error),
  ()=>this.loadFirstQuestion();
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM