json - Angular 5 中嵌套 0 索引 Json 数据的访问和绑定(bind)数据

标签 json angular5 ngfor

我正在尝试使用 Angular 5 在我的 html 中显示来自 API 的 json 结果的数据。我猜由于 json 中不必要的 0 索引,我无法执行此操作,请帮忙。 我的 json 看起来像 -

{
    "Plans": [
        [{
            "PlanId": 1,
            "PlanName": "Free"
        }, {
            "PlanId": 2,
            "PlanName": "Regular"
        }, {
            "PlanId": 3,
            "PlanName": "Premium"
        }]
    ],
    "Location": [
        [{
            "States": [{
                "StateId": 1,
                "Country_Id": 1,
                "StateName": "Alabama"
            }, {
                "StateId": 2,
                "Country_Id": 1,
                "StateName": "Alaska"
            }, {
                "StateId": 3,
                "Country_Id": 1,
                "StateName": "Arizona"
            }, {
                "StateId": 34,
                "Country_Id": 1,
                "StateName": "North Dakota"
            }, {
                "StateId": 50,
                "Country_Id": 1,
                "StateName": "Wyoming"
            }],
            "CountryId": 1,
            "CountryName": "United States of America",
            "CountryCode": "USA"
        }, {
            "States": [{
                "StateId": 51,
                "Country_Id": 2,
                "StateName": "Alberta"
            }, {
                "StateId": 52,
                "Country_Id": 2,
                "StateName": "British Columbia"
            }, {
                "StateId": 53,
                "Country_Id": 2,
                "StateName": "Manitoba"
            }, {
                "StateId": 54,
                "Country_Id": 2,
                "StateName": "New Brunswick"
            }, {
                "StateId": 63,
                "Country_Id": 2,
                "StateName": "Yukon"
            }],
            "CountryId": 2,
            "CountryName": "Canada",
            "CountryCode": "CA"
        }]
    ]
}

Image for 0 indexes I am talking about

我正在尝试动态生成 PlanNames,即“免费”、“常规”

<b>
<div class="col-md-4 text-center"*ngFor="let dummy of Plans" >
   <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.id" (change)="onSelectionChange(dummy)">Option {{dummy.PlanId}}</label>
           </div>
      </div>
   </div>
</div>
</b>

我的组件 -

`

@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 = typeof {};

   constructor (private http:HttpClient){
      this.ngOnInit().subscribe(data=>{
        console.log(data);
       this.plans = data;
      });
    }
   posts: Observable<any>;

   getPosts() {
    this.posts = this.http.get(this.apiTravelPlans) //not used
   }

  ngOnInit(){
    return this.posts = this.http.get(this.apiTravelPlans) // using to load json before my html
  };
}

`

最佳答案

缩进 JSON 后,结构就会变得更容易理解。

Plans 是一个包含单个元素的数组,它也是一个数组。

所以,如果你真的无法修复这个结构,你需要

*ngFor="let dummy of Plans[0]"

编辑:

现在您已经发布了代码,许多其他错误也变得显而易见。

您正在尝试使用模板中的Plans,但您的组件没有任何名为Plans 的属性。您有一个名为 plans 的项目,出于某种不明原因,它是用 typeof {} 初始化的(为什么?)。

您从构造函数中调用 this.ngOnInit() 。再说一次,这没有意义。 ngOnInit 是组件的一个钩子(Hook),由 Angular 自动调用。您不能调用它。它的返回类型应该是void

变量plans是异步初始化的。因此,在尝试访问它之前,您必须测试它是否已定义(或者如果将其初始化为空对象,则它的字段是否已定义)。否则,当您尝试访问稍后将异步初始化的对象的字段时,将会出现错误。

并且 plans 不是 JSON 的 Plans 字段。它是封闭的对象。

所以,简而言之,您的组件应该如下所示:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']

})
export class AppComponent implements OnInit {

 obj: any; // you should define an interface instead of using any, and choose a good name torefer to the json object

 constructor(private http: HttpClient) { }

 ngOnInit() {
    this.http.get('http://localhost:50749/api/TravelGetDetails?type=json')
      .subscribe(json => this.obj = json);
  };
}

View 应该如下所示:

<div *ngIf="obj">
  <div class="col-md-4 text-center"*ngFor="let dummy of obj.Plans[0]">
    ...
  </div>
</div>

关于json - Angular 5 中嵌套 0 索引 Json 数据的访问和绑定(bind)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48484792/

相关文章:

c++ - 为什么 boost::property_tree::write_json() 将整数值转换为字符串?这是不正确的。

Angular 5 - 添加动态路由但不路由

angular - 使用 `--prod` 构建的 ionic 滚动头包问题(请添加 @NgModule 注释。)

angular - *ng对于 html 表不起作用( Angular 2)

java - 使用 JAX-RS 通过 formParam 将 JSON 发布到 RESTful 结果为 "Unsupported Media Type"

java - 尝试序列化具有惰性获取类型的实体

php - 如何通过 medoo 库在 mysql 中搜索 json?

angular - Ngif 用于空字符串验证 Angular 5

javascript - Angular2 *ng用于推开元素的动画

Angular 6 如何将选中的复选框传递给 ngModel