如何使用角度显示测验应用程序的所有问题

时间:2019-03-26 09:01:24

标签: javascript angular typescript

我无法显示所有问题,每当我尝试开始测验时,它仅显示第一个问题并显示错误。这表明类型错误无法读取未定义的'questions'属性。每当我单击开始测验时,它就会显示第一个问题并显示错误

            - 选择 -       {{i}}。{{title.title}}     

<div class="row" *ngIf="selectQuiz">
    <div class="col s12 m6">
        <button class="btn btn-success" (click)="onSubmit()">Start Quiz</button>

        <div *ngIf="showButton">
          <div class="card-content white-text">
          <div class="card blue-grey darken-1">
            <span class="card-title">{{currentQuestion+1}}</span>
            <p>{{quiz['questions'][currentQuestion]['text']}}</p>

quizcomponent.ts

import { Component, OnInit } from '@angular/core';
import { QuizService } from '../services/quiz.service';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup } from '@angular/forms';

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

export class QuizComponent implements OnInit {
form: FormGroup;
QuizTitles = [];
Quizquestions;
selectQuiz;
quiz;
QID = [];
  answer: any;
 userData: any;
 currentQuestion = 0;
 showButton = false;
 Value;

constructor(
private router: Router,
private quizService: QuizService,
private formBuilder: FormBuilder

) {

}
getTitles() {
this.quizService.getQuiztitles().subscribe(data => {
const aData = Object.values(data);
aData.forEach((title: string, id: number) => {
 this.QuizTitles.push({
  title,
id
               });
      });

});
}
onSubmit() {
this.showButton = true;
this.quizService.getQuizQuestions(this.Value).subscribe(data => {
this.quiz = data;
console.log(this.quiz.questions[this.currentQuestion].text);
});
}


startQuiz(value) {
this.Value = value;
}
ngOnInit() {
this.getTitles();
}





OnSubmit() {
console.log(this.answer);
}
}

3 个答案:

答案 0 :(得分:0)

而不是使用

<span class="card-title">{{currentQuestion+1}}</span>
 <p>{{quiz['questions'][currentQuestion]['text']}}</p>

您应该使用 ngFor 显示所有问题,我认为问题出在

{{quiz['questions'][currentQuestion]['text']}}

您正试图在不增加反驳的情况下显示问题

更新

您正在使用订阅,将在订阅完成之前加载html文件,因此请使用加载来等待Observable获取所有数据,然后查看问题

答案 1 :(得分:0)

加载组件时,您的quiz属性不存在,因为您正在订阅中对其进行更新。

{{quiz ['questions'] [currentQuestion] ['text']}}

答案 2 :(得分:0)

首先,无需在订阅中运行foreach,您应该添加布尔变量(如ready = false),并在模板文件中添加ready = false(它不应在结束订阅和获取数据之前运行模板。 请查看代码

 getTitles() {
    this.IsLoading = true;
    this.quizService.getQuiztitles().subscribe(
      (res) => {
        this.QuizTitles= res;
        this.is_ready = true;
      },
      error => { }

    );
  }


    this.quizService.getQuizQuestions().subscribe(
      (res) => {
        this.quiz = data;
        this.is_ready_quiz = true;
      },
      error => { }

    );
  }

在html文件中

 <div *ngIf="is_ready_quiz" *ngFor="let item of quiz" >
     <p>{{item['questions'][currentQuestion]['text']}}</p>
    </div>