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');
}
}