When attempting to utilize an array in Angular 2 and Ionic 2, the objects are successfully pushed into the array. However, upon trying to access

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.

Answer №1

When it comes to loading questions, the process is asynchronous. This means that it begins by initiating the async call, without waiting for it to finish, and then moves on to execute loadFirstQuestion. As a result, you may not receive the question list immediately because it is still being loaded. One solution is to attempt calling loadfirstquestion within the subscribe function.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the mean of a group of numbers squared within an array containing multiple dimensions and then displaying the result

Recently, I've been struggling with what should be a simple problem. Despite my best efforts, I can't seem to crack it, though I feel like I'm on the right track. I'm seeking some guidance on how close I am to a solution and what steps ...

Creating sparse fieldset URL query parameters using JavaScript

Is there a way to send type-related parameters in a sparse fieldset format? I need help constructing the URL below: const page = { limit: 0, offset:10, type: { name: 's', age:'n' } } I attempted to convert the above ...

Issues with conditional types in TypeScript functionality not yielding desired results

Here is some TypeScript code that I am working with: type NumberOrNever<T> = T extends number ? T : never function f<T>(o: T) : NumberOrNever<T> { if (typeof o === "number") return o; throw "Not a number!" } ...

Tips for monitoring the loading of data in TypeScript with observers?

One of the methods in my class is responsible for fetching information from the server: public getClassesAndSubjects(school: number, whenDate: string) { this.classService.GetClassesAndSubjects(school, whenDate).subscribe(data => { if (!data.h ...

What is the most efficient way to retrieve a single type from a union that consists of either a single type or an array of types

Is there a way to determine the type of an exported union type by extracting it from an array, as illustrated in the example above? How can this be achieved without directly referencing the non-exported Type itself? interface CurrentType { a: string; b ...

Problem encountered with managing files in a 2D array of strings in C programming

I am attempting to read data from a csv file using C and then store each token in a 2D string array. The data appears to be stored correctly, but when I try to print an element from the array, I am encountering unexpected results. Below is the code snippet ...

Error in Keras input shape - providing entire array instead of individual lines

Currently, I am working on loading images from a CSV file. The images in the file are originally 300 x 300 pixels, but are flattened to 90000 pixels. I encountered an error related to the input shape while using the TensorFlow backend. I have provided link ...

An exploration on integrating a controller into an Angular directive class using Typescript

Here's the TypeScript code for an Angular directive class I've been working on: I'm wondering how I can incorporate a controller into this directive without creating a separate controller class. My goal is to write and inject the ISOLATE SC ...

Trouble installing Angular: ENOENT Error causing issues

Currently in the process of setting up angular. I have been diligently following the provided installation instructions, but when executing npm install -g @angular/cli, I encounter the error shown in the screenshot below. https://i.sstatic.net/LSP7R.jpg H ...

Creating an HTML document from JSON data is a straightforward process that involves parsing

My json object contains the following data: [ { "help": "Ensure ARIA attributes are provided", "nodes": [ { "all": [], "impact": "critical", "html": "<input id=\"chkPr ...

Unable to correctly import a TypeScript class into a React project

I have encountered an issue where I am unable to assign a default value to a TypeScript Class in my React Project (Docusaurus). It works with: class Test { private hello: string; constructor() { this.hello = "hi"; } } However, it does ...

Struggling to compile your Angular 2 application in Visual Studio 2015?

After carefully following all the steps outlined in the VISUAL STUDIO 2015 QUICKSTART documentation, I have also gone ahead and installed the "Microsoft .NET Core 1.0.1 VS 2015 Tooling Preview 2", even though it was not specifically mentioned in the docume ...

Creating a standard change listener for text entry fields utilizing Typescript and React with a dictionary data type

I came across an interesting example of using a single change function to manage multiple text inputs and state changes in React and Typescript. The example demonstrates the use of a standard string type: type MyEntity = { name: string; // can be app ...

What is the best way to ensure that a div containing lengthy text wraps to the next line as if it were only text overflow?

Is there a way to make a div or span within another div act as text, causing overflow to shift to the next line? I'm unsure of which CSS properties would achieve this effect. I've attempted using overflow-wrap: break-word; word-break: break-al ...

The name 'BrowseAnimationModule' cannot be located

Can someone help me figure out how to install or fix this import issue I'm having with the 'animations' directory in @angular/platform-browser/animations not importing properly? import {CommonModule} from '@angular/common'; import ...

Encountering the error message "Error: 'preserveValueImports' is an unknown compiler option" while setting up a SvelteKit project

https://i.stack.imgur.com/fnidk.png Every time I set up a new sveltekit project using TypeScript, I keep encountering the error "Unknown compiler option 'preserveValueImports'.ts" in the tsconfig.json file. The error shows up above the line wher ...

What techniques can be applied to utilize JSON data in order to dynamically create menu components using the map method?

My current challenge involves dynamically generating a set of menu items using data retrieved from a JSON file. I've attempted to achieve this by mapping the values with props, but it seems like I'm overlooking something. Below is the code snipp ...

Flattening arrays using JSON_TO_ARRAY in SingleStore (formerly known as MemSQL)

I have a table source: data { "results": { "rows": [ { "title": "A", "count": 61 }, { "title": "B", "count": 9 } ] }} { "results": { "rows": [ { &q ...

Guide to navigating to a specific route based on location in a Node.js Express application

Currently, I am integrating the official i18n library to localize my Angular Universal application and utilizing a proxy to deliver the localized versions. The app is functioning properly when there is a language specified in the URL (e.g: /en/page), but e ...

How can you efficiently enable Angular 4 routing on a production server?

It took me a dedicated 6 days to transition an HTML5-only app into an Angular 4 routing application, all in the hopes of enhancing its SEO capabilities. However, upon deployment, I discovered that direct URLs were resulting in frustrating 404 pages. For e ...