Angular通过HTTP GET按ID获取JSON后如何展示指定字段值
问题根因
- 接口类型定义不匹配:你定义的
problemSer接口存在多余字段name,且解决方案字段名写为solution,但接口实际返回字段是solutions - 服务返回类型错误:按ID查询单条数据的接口返回的是单个对象,不是
problemSer[]数组类型 - 组件赋值逻辑错误:接口返回的data本身就是目标数据对象,你错误取值
data.services,而返回结构里根本没有services字段,导致services数组始终为空
修复步骤
1. 修正problemSer接口定义
export interface problemSer{ _id: string, serviceProblem: string, causes: any[], solutions: any[], createdAt: string }
2. 修正服务层service.ts的请求方法
httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } // 返回类型改为单个problemSer对象 get(id: any): Observable<problemSer> { return this.http.get<problemSer>(`${baseUrl}/${id}`, this.httpOptions) }
3. 修正组件component.ts逻辑
方案A:直接使用单对象存储(适合单条ID查询场景)
// 改为单对象,初始值设为null problemDetail: problemSer | null = null; ngOnInit(){ this.getProblem("6154517d04dc7ac70253e2a8"); } getProblem(id: any){ this.problemService.get(id) .subscribe((data: problemSer) => { // 直接赋值返回的data,不需要取data.services this.problemDetail = data; console.log(data); }); }
方案B:保留数组格式(适合后续扩展多条查询场景)
services: problemSer[]=[]; ngOnInit(){ this.getProblem("6154517d04dc7ac70253e2a8"); } getProblem(id: any){ this.problemService.get(id) .subscribe((data: problemSer) => { // 把返回的单对象塞进数组 this.services = [data]; console.log(data); }); }
4. 修正模板代码
对应方案A的模板(不需要ngFor遍历单条数据)
<!-- 直接展示单个字段 --> <p>问题描述:{{problemDetail?.serviceProblem}}</p> <!-- 遍历solutions数组展示解决方案 --> <ul> <li *ngFor="let solution of problemDetail?.solutions">{{solution}}</li> </ul>
对应方案B的模板(保留原ngFor逻辑)
<ul > <li *ngFor="let problem of services"> {{problem.serviceProblem}} </li> </ul> <!-- 单独遍历solutions示例 --> <ul *ngIf="services.length"> <li *ngFor="let solution of services[0].solutions">{{solution}}</li> </ul>
内容的提问来源于stack exchange,提问作者rom
相关产品推荐
相关产品推荐

