从api调用通过服务返回到组件的数据是一个对象,似乎需要是一个Angular数组 [英] Data returning from api call through service to component is an object and seems to need to be an Array for Angular
问题描述
我有数据返回给我,工作得很好
I have data returned to me that works just fine
工作数据是
数据:数组(16)
无法正常工作的数据是这样的
Data that is NOT working is like this
data:Menu1Items:Array(5)> 0 {....}等
我使用的是Angular 5,所以服务返回这样的数据
I am using Angular 5, and so service returns data like this
.map((response: Response) => {
return response;
然后组件拦截它并且console.log工作正常
Then the component intercepts it and console.log works fine
this.arsSevice.getMenu()
.subscribe(
result => {
this.testing = result;
console.log('menu',result);
})
问题与数据有关,此截图显示问题,我只是不知道了解如何使用对象vs数组修复它?
problem is with the data, this screenshot shows the problem, i just don't understand how to fix it with the object vs array?
仅因为HTML模板错误消息
error message ONLY because of the HTML TEMPLATE
找不到'object'类型的不同支持对象'[object Object]'。NgFor只支持绑定到Iterables,例如Arrays。
HTML模板
<li *ngFor="let item of testing">
图片显示在体系结构上与html模板循环,组件相似的呼叫,为工作呼叫提供服务是BOTTOM,组件
注意与我遇到问题的菜单
相比有什么不同?
Image showing that a call that is similar in architecture with html template loop, component , service the working call is the BOTTOM , component
notice the different compared to the one called menu
that I'm having trouble with?
推荐答案
我认为你需要设置testing = result.data,然后迭代它。
I think you need to set testing = result.data, and iterate through that.
this.arsSevice.getMenu()
.subscribe(
result => {
this.testing = result.data;
})
这将使您可以访问数据中的数组
this will give you access to the array in 'data'
我试图改变形状数据,这对我有用。希望它适合你...
I tried to change the shape of the data, and this worked for me. Hopefully it works for you...
var data={
menu1Items:[{key:"boo", key2:"hoo"}],
menu2Items:[{key:"boo2", key2:"hoo2"}]
}
var tempData:any[]=[];
for(var key in data){
if(data.hasOwnProperty(key)){
tempData.push(data[key]);
}
}
this.data = tempData;
}
在您的模板中:
<ul *ngFor="let menu of data ">
<li>
<ng-container *ngFor="let menuItem of menu">
{{menuItem.key}} / {{ menuItem.key2}}
</ng-container>
</li>
</ul>
这篇关于从api调用通过服务返回到组件的数据是一个对象,似乎需要是一个Angular数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!