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

Angular 5中绑定嵌套0索引JSON数据并展示API返回内容

解决Angular 5中展示嵌套JSON数据的问题

先帮你理清楚问题根源:你的JSON结构里,Plans是数组套数组的嵌套结构——外层Plans是一个数组,它的第一个元素才是真正包含所有Plan对象的数组。你现在直接遍历Plans,拿到的是那个内层数组,自然取不到PlanName这类属性。

下面给你两种可行的解决方案,还有代码里的小问题修正:

方案一:直接在模板中访问内层数组

修改HTML模板里的*ngFor遍历对象,直接指向plans.Plans[0](也就是真正存Plan对象的数组),同时修正你模板里的一个小错误([value]="dummy.id"应该是dummy.PlanId):

<div class="col-md-4 text-center" *ngFor="let dummy of plans.Plans[0]; let idx = index" >
  <div class="panel panel-pricing" >
    <div class="panel-heading" >
      <h3>{{dummy.PlanName}}</h3>
    </div>
    <div class="panel-body text-center">
      <p><strong>$100 / Month</strong></p>
    </div>
    <div class="panel-footer">
      <div class="radio">
        <label>
          <input type="radio" name="planradiogroup" id="planradio{{dummy.PlanId}}" 
                 [checked]="idx === 0" [value]="dummy.PlanId" 
                 (change)="onSelectionChange(dummy)">
          Option {{dummy.PlanId}}
        </label>
      </div>
    </div>
  </div>
</div>

方案二:在组件中预处理数据(更推荐)

如果后续还有其他地方要用到Plan数据,建议在组件里把嵌套数组扁平化,避免模板里写[0]这种硬编码,代码可读性更好:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  readonly apiTravelPlans = "http://localhost:50749/api/TravelGetDetails?type=json";
  plans: any = {};
  // 新增变量存储扁平化后的Plan列表
  planList: any[] = [];

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get(this.apiTravelPlans).subscribe(data => {
      console.log(data);
      this.plans = data;
      // 取出嵌套数组里的真实数据
      this.planList = this.plans.Plans[0];
    });
  }

  onSelectionChange(plan: any) {
    // 这里可以处理选中事件的逻辑
    console.log('选中的方案:', plan);
  }
}

之后模板里直接遍历planList即可:

<div class="col-md-4 text-center" *ngFor="let dummy of planList; let idx = index" >
  <!-- 内容和方案一一致 -->
</div>

顺便修正你组件里的几个小问题

你原来的组件代码有几个不规范的地方:

  1. 不要在constructor里手动调用ngOnInit()——这是Angular的生命周期钩子,会由框架自动触发
  2. posts变量和getPosts()方法没用到,可以删掉简化代码
  3. plans: any = typeof {};写法没必要,直接plans: any = {};就可以,要是想更规范还可以定义对应的接口类型

关于Location数据的处理思路

如果后续要展示Location里的内容,逻辑是完全一样的:Location[0]才是包含国家和States的数组,用同样的扁平化方式处理即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:44:29