首页 > 解决方案 > 如何使用 *ngFor 获取 json 数据 X 次

问题描述

我想从我的端点获取 3 张图像,其中有很多使用 angular *ngFor(或任何其他可用方法)的图像

这是我的 component.html

<div class="col-sm-4 col-xs-6" *ngFor="let result of data.response.constructor(3)">
  <div class="panel-thumbnail"><img class="img-responsive"  width="200" [src]="result.thumbnail"></div>
 </div>

ts文件

export class HomeComponent implements OnInit {
public data:any = []
constructor(private http: HttpClient) {}
getData(){
  const url ='myUrl'
this.http.get(url).subscribe((res)=>{
  this.data = res
  console.log(this.data)
})}
ngOnInit(): void {
 this.getData()}}

我尝试按照其他帖子的建议使用 [].constructor(3) ,但我没有得到任何结果。有人可以帮忙吗

标签: htmlangular

解决方案


您可以使用 slice 来获取具有预期项目数的数组

<div class="col-sm-4 col-xs-6" *ngFor="let result of data.response.slice(0,3)">
  <div class="panel-thumbnail"><img class="img-responsive"  width="200" [src]="result.thumbnail"></div>
 </div>

语法是

array.slice(first, numberOfElement)

推荐阅读