我正在尝试制作测验应用程序。我需要按顺序显示问题列表而不是列表。我无法显示{{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>
答案 0 :(得分:0)
您尝试显示的信息存在的问题是,初始化组件并执行question: string = this.question[0].question
时毫无疑问。
如果要将第一个问题存储在question
内,则需要在subscribe
方法中也添加该行,如下所示:
getQuestions(): void{
this.questionService
.getQuestions()
.subscribe(questions => {
this.questions = questions;
this.question = this.questions[0].question;
});
}
因此,通过这种方式,可以确保在初始化数据时数据在那里。
希望有帮助!