I receive a list of objects from the server and I need to display them in turn, and not immediately with a list. I make a simple questionnaire. I want at the moment that the first question is displayed after the page loads, but I can’t get the first value out of the questions in the controller as I have to wait for the list to load. How to do it right?

вот контроллер: questionform.componetn.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> 
  • Well, wait, what's the problem? - Roman Danilov

1 answer 1

I think you should have a print there like this: question: string = this.questions [0] .question; But that's not the point here so that when receiving data from the server, do the assignment right away. For example:

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

questionform.component.html

 <div *ngIf="question"> <p>{{question}}</p> <button onClick()="next()">next</button> </div> 
  • Thank! did not know that you can immediately make the assignment so This solved my problem. - False True