[英]Trouble while fetching data from API in Angular
我正在尝试从 API 获取数据,当我 console.log() 它时,我在控制台中获取数据,但是当我尝试在我的表中获取它时,我收到以下错误:错误错误:尝试错误差异'[对象对象]'。 仅允许 arrays 和可迭代对象
我的 ts 文件
CovidPatients:any=[];
show() {
this.http.get('https:API-URL').subscribe(responseData=>{
const data1=JSON.stringify(responseData)
this.CovidPatients=JSON.parse(data1)
console.log(data1);
})
}
html
<tr *ngFor="let data of CovidPatients">
<td>{{data.agebracket}}</td>
<td>{{data.contractedfromwhichpatientsuspected}}</td>
<td>{{data.currentstatus}}</td>
<tr>
在 API 中,数据位于嵌套数组中,我认为这可能是问题所在:
{
"raw_data": [
{
"agebracket": "",
"contractedfromwhichpatientsuspected": "",
"currentstatus": "Hospitalized",
"dateannounced": "10/05/2020",
"detectedcity": "",
"detecteddistrict": "",
"detectedstate": "",
"entryid": "",
"gender": "",
"nationality": "",
"notes": "",
"numcases": "2",
"patientnumber": "37900",
"source1": "https://twitter.com/ANI/status/1259331384851775488?s=09",
"source2": "",
"source3": "",
"statecode": "RJ",
"statepatientnumber": "",
"statuschangedate": "",
"typeoftransmission": ""
},
{
"agebracket": "",
"contractedfromwhichpatientsuspected": "",.....................
如何在表格中显示数据。
CovidPatients
不是一个数组。 将您的 for 循环更改为:
<tr *ngFor="let data of CovidPatients.raw_data">
您可以执行以下操作,
show() {
this.http.get('https:API-URL').subscribe(responseData => {
this.CovidPatients = responseData['raw_data']
console.log(this.CovidPatients);
})}
然后在您的模板文件中,您可以使用 *ngFor 结构指令遍历数组,
<tbody *ngFor="let data of CovidPatients">
<tr>
<td>{{data.agebracket}}</td>
<td>{{data.contractedfromwhichpatientsuspected}}</td>
<td>{{data.currentstatus}}</td>
</tr>
<tbody>
JSON.stringify
和JSON.parse
当且仅当您在响应中获得 JSON2668CFDE63131B459 在*ngFor
中,如果不使用键值keyvalue
,则可以迭代 object 的数组。 在你的 JSON object raw_data
是数组,所以你可以这样尝试
<tr *ngFor="let data of CovidPatients.raw_data">
{{data.agebracket}}
.
.
.
</tr>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.