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

如何将REST API返回的JSON响应转换为Angular模型

Angular对应模型定义方案

在Angular中通常使用TypeScript接口定义与JSON结构匹配的模型,你可以按照嵌套层级从内到外定义如下:

1. 嵌套国家模型

对应JSON中的country字段结构:

interface Country {
  id: number;
  name: string;
}

2. 业务数据项模型

对应data数组中的单个元素结构:

interface BusinessItem {
  id: number;
  country_id: number;
  name: string;
  address: string;
  isActive: number; // 接口返回值为1/0,如需布尔类型可在请求返回后做转换
  created_at: string; // ISO格式时间字符串,可手动实例化为Date类型使用
  updated_at: string;
  country: Country;
}

3. 最外层API响应模型

对应整个JSON响应的结构:

interface ApiResponse {
  data: BusinessItem[];
  message: string;
  status: boolean;
}

使用示例

你可以直接在Angular的HttpClient请求中指定返回类型,获得完整的类型提示:

// 业务服务请求示例
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class BusinessService {
  constructor(private http: HttpClient) {}

  getBusinessList(): Observable<ApiResponse> {
    return this.http.get<ApiResponse>('你的API接口地址');
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:48:05