What is the best way to retrieve an element from an array that was obtained via an http.get request?

Upon making an http get request in Angular, I received an array of Question objects. However, I am encountering an issue where I cannot access an element from it due to the error message:

Cannot read property '0' of undefined
. My assumption is that since the request is asynchronous, the data might not be fully loaded when I try to retrieve the element.

Below is my component where I fetch the questions array and attempt to extract the current question:

import { formatDate } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { IndividualSession } from 'src/app/_models/individual-session';
import { Question } from 'src/app/_models/question';
import { User } from 'src/app/_models/user';
import { AccountService } from 'src/app/_services/account.service';
import { IndividualSessionService } from 'src/app/_services/individual-session.service';
import { NavbarService } from 'src/app/_services/navbar.service';
import { QuestionsService } from 'src/app/_services/questions.service';
import { UsersService } from 'src/app/_services/users.service';

@Component({
  selector: 'app-exam-in-progress',
  templateUrl: './exam-in-progress.component.html',
  styleUrls: ['./exam-in-progress.component.css']
})

export class ExamInProgressComponent implements OnInit {
  individualSession: IndividualSession;
  user: User;
  currentUser$: Observable<User>;
  questions: Question[];
  currentQuestion: Question;

  constructor(public navService: NavbarService, 
    public individualSessionService: IndividualSessionService,
    public userService: UsersService,
    public accountService: AccountService,
    private questionService: QuestionsService) { }

  ngOnInit(): void {
    this.navService.hide();

    this.startNewSession();
  }

  private startNewSession() {
    this.getCurrentUserData();

    if (localStorage.getItem('currentIndividualSession') === null) {
      this.individualSession = <IndividualSession>{
        ability: 0.5,
        standardError: 1,
        startTime: formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss', 'en-us'),
        examineeId: 1,
        sessionId: 1
      };

      localStorage.setItem('currentIndividualSession', JSON.stringify(this.individualSession));
    }

    let json = localStorage.getItem('currentIndividualSession');
    this.individualSession = JSON.parse(json);
    this.loadQuestions();

    this.currentQuestion = this.questions[0];
  }

  stopTest() {
    this.navService.show();
  }

  onNextClick() {
    this.individualSession.standardError -= 0.1;
  }

  private getCurrentUserData() {
    this.currentUser$ = this.accountService.currentUser$;
    this.currentUser$.subscribe(currUser => {
      if(!!currUser) {
        this.loadUser(currUser.email);
      }
    })
  }

  loadUser(email: string) {
    this.userService.getUser(email).subscribe(user => {
      this.user = user;
    })
  }

  loadQuestions() {
    this.questionService.getQuestionsFromQuestionnaire(1).subscribe(questions => {
      this.questions = questions;
    });
  }


}

And here's my service implementation:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { Question } from '../_models/question';

@Injectable({
  providedIn: 'root'
})
export class QuestionsService {
  baseUrl = environment.apiUrl;

  constructor(private http: HttpClient) { }

  getQuestionsFromQuestionnaire(questionnaireId: number): Observable<Question[]> {
    return this.http.get<Question[]>(this.baseUrl + 'questionnaires/' + questionnaireId + '/questions');
  }
}

Answer №1

Are you willing to give it a shot?

loadQuestions() {
   this.questionService.getQuestionsFromQuestionnaire(1).subscribe(questions => {
      this.questions = questions;
      this.currentQuestion = this.questions[0];
   });
}

Also, make sure to eliminate

this.currentQuestion = this.questions[0];
from the startNewSession() function.

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

The argument array for std::async is disturbed

I need to divide a vector into smaller vectors, process each of them separately on a thread, and then combine them back together. I am utilizing std::async to create threads and my code implementation is as follows: void process(std::vector<int>& ...

Incorporate a progress bar into the Material-UI table design

I have the following example of a Material-UI table: import React from "react"; import clsx from "clsx"; import { createStyles, lighten, makeStyles, Theme } from "@material-ui/core/styles"; import Table from "@mat ...

Can you explain the concept of F-Bounded Polymorphism in TypeScript?

Version 1.8 of TypeScript caught my attention because it now supports F-Bounded Polymorphism. Can you help me understand what this feature is in simple terms and how it can be beneficial? I assume that its early inclusion signifies its significance. ...

The TypeScript compiler encounters difficulties in locating type definitions when utilizing an inherited tsconfig file

There seems to be an issue with the functionality of tsconfig.json inheritance, specifically regarding the proper inheritance of the "typeRoots" setting. http://www.typescriptlang.org/docs/handbook/tsconfig-json.html (folder structure provided below) we ...

Do you think it's important to include a maxlength validation message for an input field in Angular?

Utilizing the maxlength attribute on a form field not only enables Angular's default validation, it also restricts input beyond the specified length from being typed into the text box. So, does this imply that displaying an error message for violating ...

Tips for pulling out specific keys from a typed object using an index signature

TL;DR Query: How do I create a type converter in TypeScript that extracts the defined keys from objects typed with index signatures? I am looking to develop a type "converter" in TypeScript that takes a type A as input and outputs a new type B with keys ...

Tips for integrating 2 way data binding into model-driven forms

When working with Angular 2, one approach to creating forms is the model-driven method. This means that controls may lose their two-way data binding, unlike in the template-driven approach with ngModel. What is the best way to combine two-way data binding ...

Angular 4's async pipe triggers an endless loop when used in conjunction with a method call

How can I create a select UI element with dynamic options using a method that returns an observable based on the inputs provided? TypeScript (Component class) retrieveCars(type : string, engine : string) : Observable<Cars>{ return this.carServi ...

Module 'framer' missing even after removing node modules directory

While cleaning up the angular code, I decided to delete some unused custom modules. However, after doing so, I encountered an error regarding a deleted imported component in app.module.ts even though it had already been removed from the imports. To addres ...

Exploring limitless possibilities with Vue slot manipulation

Imagine I am looking to develop a multi-layered Component for reusability, similar to a 'Tab' UI. This would allow developers to use it like this: <tabs> <tab label="My First Tab"> Content for first tab which could co ...

Error message: When using Vue CLI in conjunction with Axios, a TypeError occurs stating that XX

I recently started working with Vue.js and wanted to set up a Vue CLI project with Axios for handling HTTP requests. I came across this helpful guide which provided a good starting point, especially since I plan on creating a large project that can be reus ...

Issues arising post transitioning to 14.0.0 from 13.0.0 version of ngx-masonry library leading to failed tests

Following the update to the latest stable version of the library ngx-masonry 14.0.0, our tests started failing. The release was just yesterday (24.10.2022) and you can find the changelog here: https://github.com/wynfred/ngx-masonry/blob/master/CHANGELOG.md ...

Exploring the world of asynchronous operations with React Hooks

Hello, I am a beginner when it comes to React and JavaScript. I could really use some assistance with two hooks that I have created: useSaveStorage and useGetStorage. The issue I am facing is that my app is supposed to receive data and save it into AsyncS ...

How to efficiently test a series of HTTP requests in Angular 6

I have developed a new feature that retrieves user information from django rest auth. To achieve this, I need to make 2 separate requests - one for fetching the authentication token and another for obtaining user information. Within the userService servic ...

Dealing with a sequence of deletions in Angular 4

When working with a ReplaySubject of size 3 and a delete chain that must be in order, I encountered an issue. After the deletion process is completed, I need to redirect the user. However, when subscribing to this ReplaySubject method, it sends "here fin ...

The Angular AOT compilation process is causing essential code to be stripped away from the openlayers

We have recently updated our project to use Angular 7 along with openlayers 5.3, and so far everything has been running smoothly. In an effort to improve initial loading times, we implemented several optimizations during the build process, including enabli ...

Angular throws an error when trying to parse undefined data outside of an async function

I'm having trouble parsing data retrieved from an http call and passing it to ngOnInit. Can you assist me in finding a solution? My project is built with Angular 4. Here's the async function: async getAsyncData() { this.asyncResult = awai ...

Utilizing an external library in a Typescript 2.0 project: A comprehensive guide

I am currently working on a Typescript 2.0 project that utilizes Common JS modules and System JS loader. My IDE of choice is Visual Studio code. I am encountering a challenge with integrating an external library (filesaver JS) into my project. After insta ...

The attribute 'X' is not present in the specified type 'IntrinsicAttributes & InferPropsInner'

I've been restructuring my code from a .js file to a .tsx file, as seen below: import React, { useEffect, useState } from 'react' import PropTypes from 'prop-types' import { checkMobile } from '../../utils/common' import ...

I keep encountering the ExpressionChangedAfterItHasBeenCheckedError error in Angular, even though I'm calling it before the view is checked. What could

This is a piece of code that I have been working on home-component.ts export class HomeComponent implements OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked { loading = false; constructor() { } ngOn ...