显示信息 Angular 6

Displaing information Angular 6

我正在尝试制作测验应用程序。我需要按顺序显示问题列表而不是列表。我无法制作 {{question}} 显示,因为在服务正常运行之前它是未定义的。怎么做才对?

questionform.component.ts

import { Component, OnInit } from '@angular/core';
import {Question} from "../question";
import {questionService} from "../question.service";

@Component({
  selector: 'app-questionform',
  templateUrl: './questionform.component.html',
  styleUrls: ['./questionform.component.css']
})
export class QuestionformComponent implements OnInit {

  questions: Question[];
  question: string = this.question[0].question;

  constructor(private questionService: QuestionService) { }

  ngOnInit() {
    this.getQuestions();
  }

  getQuestions(): void{
    this.questionService.getQuestions().subscribe(questions => this.questions = questions);
  }

}

questionform.component.html

<p>{{question}}</p>
<button onClick()="next()">next</button>

您尝试显示的信息的问题是组件初始化和执行question: string = this.question[0].question时没有问题。

如果您想将第一个问题存储在 question 中,您还需要在 subscribe 方法中添加该行,如下所示:

getQuestions(): void{
    this.questionService
        .getQuestions()
        .subscribe(questions => {
            this.questions = questions;
            this.question = this.questions[0].question;
         });
}

因此,通过这种方式,您可以确保在初始化数据时数据就在那里。

希望对您有所帮助!