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

Angular中TypeScript类从API获取JSON数据的实现求助

解决从API获取FAQ数据的问题

你好!作为TypeScript和Angular新手,这里的核心问题是原代码直接把fetch的结果赋值给了static data,但fetch返回的是一个Promise,不是你需要的数组数据——这就导致组件无法像使用静态数组那样直接拿到可用的FAQ列表。下面给你两种可行的方案,适配不同的使用场景:

方案1:基于原生fetch的Promise实现

如果你想继续使用原生fetch,可以把原来的静态data改成一个异步方法,这样就能正确获取并返回API的JSON数组:

export class FaqFakeDb {
  // 定义数据类型,让TypeScript有类型提示
  public static async getData(): Promise<Array<{id: string, question: string, answer: string}>> {
    try {
      // 发起请求并等待响应
      const response = await fetch('https://#######.co.uk/api/faq/');
      
      // 检查请求是否成功
      if (!response.ok) {
        throw new Error(`请求失败!状态码:${response.status}`);
      }
      
      // 解析JSON数据并返回
      const data = await response.json();
      return data;
    } catch (error) {
      // 捕获错误,避免页面崩溃,同时返回原静态数据作为降级方案
      console.error('获取FAQ数据失败:', error);
      return [
        { "id":"1", "question":"test1", "answer":"test1" },
        { "id":"2", "question":"test1", "answer":"test1" },
        { "id":"3", "question":"test1", "answer":"test1" }
      ];
    }
  }
}

在组件中使用:

因为getData是异步方法,你需要用async/await来获取数据:

import { FaqFakeDb } from './path-to-faq-fake-db';
import { OnInit } from '@angular/core';

export class FaqComponent implements OnInit {
  faqData: Array<{id: string, question: string, answer: string}> = [];

  async ngOnInit() {
    // 等待数据返回后赋值
    this.faqData = await FaqFakeDb.getData();
  }
}

方案2:推荐使用Angular的HttpClient(更符合Angular生态)

Angular自带的HttpClient是为框架量身设计的,支持RxJS异步流、内置错误处理、请求拦截等功能,比原生fetch更适合Angular项目。我们可以把原来的FaqFakeDb改成一个服务:

第一步:创建FAQ服务

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class FaqService {
  // 降级用的静态数据
  private fallbackFaqData = [
    { "id":"1", "question":"test1", "answer":"test1" },
    { "id":"2", "question":"test1", "answer":"test1" },
    { "id":"3", "question":"test1", "answer":"test1" }
  ];

  constructor(private http: HttpClient) {}

  getFaqData(): Observable<Array<{id: string, question: string, answer: string}>> {
    return this.http.get<Array<{id: string, question: string, answer: string}>>('https://#######.co.uk/api/faq/')
      .pipe(
        // 请求失败时返回降级数据
        catchError(error => {
          console.error('获取FAQ数据失败:', error);
          return of(this.fallbackFaqData);
        })
      );
  }
}

第二步:在组件中使用服务

import { FaqService } from './path-to-faq-service';
import { OnInit } from '@angular/core';

export class FaqComponent implements OnInit {
  faqData: Array<{id: string, question: string, answer: string}> = [];

  // 注入服务
  constructor(private faqService: FaqService) {}

  ngOnInit() {
    // 订阅Observable获取数据
    this.faqService.getFaqData().subscribe(data => {
      this.faqData = data;
    });
  }
}

额外步骤:别忘了导入HttpClientModule

在你的根模块(比如AppModule)中导入HttpClientModule,否则HttpClient无法使用:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    // ...其他模块
    HttpClientModule
  ]
})
export class AppModule { }

两种方案都能实现和原静态数组相同的功能——组件最终会拿到一个FAQ数组用于渲染。推荐方案2,因为它更贴合Angular的开发习惯,也更容易扩展(比如添加请求拦截、缓存等功能)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:31:51