gpt4 book ai didi

javascript - Angular 4 : Load data from Json

转载 作者:行者123 更新时间:2023-11-30 11:37:58 25 4
gpt4 key购买 nike

我是 Angular 的新手。我正在做的是在点击时从 json 文件加载数据,到目前为止我已经正确地完成了。

但是我卡住的地方是在点击之前加载第一个json对象,即在页面加载时加载第一个对象

typescript

export class RequestComponent{
people: Object[];
constructor(http:Http){
http.get('data.json').subscribe(res => {
this.people = res.json();
});
}

public currentStatus;
public setThis = (people) => this.currentStatus = people;
}

HTML

  <ul class="col-md-4">
<li *ngFor="let person of people" (click)="setThis(person)">
<span><i class="fa fa-cog" aria-hidden="true"></i></span>
<p>{{ person.name }}</p>
</li>
</ul>
<div *ngIf="currentStatus" class="col-md-8 right-section">
<h2>{{ currentStatus.name }}</h2>
<img [src]="currentStatus.img" class="img-responsive"/>
</div>

最佳答案

尝试在 ngOnInit() 函数中加载 json。

import { Component, OnInit } from '@angular/core';
// other imports

export class RequestComponent implements ngOnInit{
people: Object[];

constructor(private http:Http){}

ngOnInit(){
this.http.get('data.json').subscribe(res => {
this.people = res.json();
});
}
}

并添加 ngIf 来显示您的记录,因此它不会在加载 people 之前尝试显示它。

<ul *ngIf="people" class="col-md-4">
<li *ngFor="let person of people" (click)="setThis(person)">
<span><i class="fa fa-cog" aria-hidden="true"></i></span>
<p>{{ person.name }}</p>
</li>
</ul>
<div *ngIf="currentStatus" class="col-md-8 right-section">
<h2>{{ currentStatus.name }}</h2>
<img [src]="currentStatus.img" class="img-responsive" />
</div>

关于javascript - Angular 4 : Load data from Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43688895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com