首先,确保在API调用中获取到了正确的JSON响应。然后,您需要在组件中创建一个数组,并将JSON响应push到该数组中。最后,在HTML中使用ngFor指令循环遍历该数组并显示JSON数据。以下是一个示例代码:
// 在组件中
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
data: any[] = [];
constructor(private apiService: ApiService) {}
ngOnInit() {
this.apiService.getData().subscribe(
(response) => {
this.data = response;
},
(error) => {
console.log(error);
}
);
}
}
// 在HTML中
- {{ item }}
在此示例中,ApiService是用于API调用的服务。getData()方法返回一个可观察对象,该对象被订阅以获取JSON响应。在响应中,我们将数据存储在组件中的data数组中,并通过ngFor指令在HTML中遍历并显示数据。