You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中每次仅展示API返回的单条数据实例?

Angular 实现单题切换展示方案

先修正你的API数据结构

你给出的JSON格式存在语法错误,正确的结构应该是questions为数组,每个问题对象包含question和options字段,示例如下:

{
  "questions": [
    {
      "question": "What is 2+2?",
      "options": [2, 6, 1]
    },
    {
      "question": "What is the capitol of Sweden?",
      "options": ["Stockholm", "South America", "Oceania"]
    }
  ]
}

组件实现步骤

1. 组件类(.ts)

定义当前问题索引、问题数组,实现API数据获取和下一题切换逻辑:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-quiz',
  templateUrl: './quiz.component.html',
  styleUrls: ['./quiz.component.css']
})
export class QuizComponent implements OnInit {
  questions: any[] = [];
  currentIndex = 0;

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    // 调用API获取数据
    this.http.get('你的API地址').subscribe((res: any) => {
      this.questions = res.questions;
    });
  }

  nextQuestion(): void {
    // 判断是否还有下一题
    if (this.currentIndex < this.questions.length - 1) {
      this.currentIndex++;
    }
  }
}

2. 模板文件(.html)

通过currentIndex控制当前展示的问题,用*ngFor遍历当前问题的选项:

<div *ngIf="questions.length > 0">
  <h2>{{ questions[currentIndex].question }}</h2>
  <div *ngFor="let option of questions[currentIndex].options; let idx = index">
    <p>Option {{ idx + 1 }}: {{ option }}</p>
  </div>
  <button 
    (click)="nextQuestion()"
    [disabled]="currentIndex === questions.length - 1"
  >
    {{ currentIndex === questions.length - 1 ? '已完成' : '下一题' }}
  </button>
</div>
<div *ngIf="questions.length === 0">加载中...</div>

关键说明

  • 你完全可以用*ngFor:它用来遍历当前问题的选项,而问题的切换是通过修改currentIndex来控制展示哪一组数据,两者并不冲突。
  • 动态适配问题数量:只要API返回的questions数组长度变化,组件会自动适配,最后一题时按钮会禁用并提示“已完成”。
  • 用*ngIf处理加载状态和空数据情况,提升用户体验。

内容的提问来源于stack exchange,提问作者GreGu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 09:20:35