![](/img/trans.png)
[英]Angular 5 Service is returning data from api , but Component is not showing me the data
[英]Data returning from api call through service to component is an object and seems to need to be an Array for Angular
我有返回的數據可以正常工作
工作數據是
data: Array(16)
無效的數據是這樣的
data: Menu1Items: Array(5) > 0 { .... } etc
我正在使用Angular 5,因此服務返回這樣的數據
.map((response: Response) => {
return response;
然后組件攔截它,console.log正常工作
this.arsSevice.getMenu()
.subscribe(
result => {
this.testing = result;
console.log('menu',result);
})
問題在於數據,此屏幕快照顯示了問題,我只是不了解如何使用對象vs數組修復它?
錯誤消息僅由於HTML模板
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
HTML模板
<li *ngFor="let item of testing">
該圖顯示了與html模板循環,組件,服務的體系結構中的調用類似的調用是BOTTOM, component
注意到與我遇到麻煩的一個稱為menu
不同嗎?
我認為您需要設置testing = result.data,然后進行迭代。
this.arsSevice.getMenu()
.subscribe(
result => {
this.testing = result.data;
})
這將使您可以訪問“數據”中的數組
我試圖更改數據的形狀,這對我有用。 希望它對您有用...
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>
使用HttpClient時,angular會自動將響應解析為一個對象。 它不知道對象是什么類型,因此它只是一個不知道其數組屬性的普通對象。
這是因為,盡管HttpClient將JSON響應解析為一個對象,但它不知道該對象是什么形狀。
但是您可以告訴angular返回的對象是什么類型,以便正確投射。 例如,如果您返回一個字符串數組,則可以執行以下操作。
return this.http.get<string[]>(apiUrl)
您可以在這里閱讀更多內容,它們描述的是類似的問題,只是結構略有不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.