![](/img/trans.png)
[英]angular 2 how to assign an array of JSON response using Observable and map in typescript interface and retrieve in html using *ngFor?
[英]Assign array of JSON objects to array of interface Angular/Typescript
目前,這有效並且在運行時不會出現我的錯誤,但我的文本編輯器給了我一個錯誤,說類型“CategoryInterface[]”上不存在屬性“categories”(在 response.categories 分配給變量的那一行) ) 所以我不確定我是否做對了。
public categories: CategoryInterface[];
.subscribe((response: CategoryInterface[]) => {
this.categories = response.categories;
console.log(this.categories);
});
我的后端返回這個:
{
"categories": [
{
"categoryId": 1,
"name": "Important",
"description": "This category is important.",
"order": 1,
"createdBy": null,
"createdAt": "2017-11-25 12:09:04",
"updatedBy": null,
"updatedAt": "2018-01-17 23:53:25",
"categoryBoards": [
{
"categoryBoardId": 1,
"categoryId": 1,
"name": "Announcements",
"description": null,
"order": 2,
"createdBy": null,
"createdAt": "2017-11-25 12:09:49",
"updatedBy": null,
"updatedAt": "2018-01-18 00:09:02"
},
{
"categoryBoardId": 23,
"categoryId": 1,
"name": "Rules",
"description": null,
"order": 1,
"createdBy": null,
"createdAt": "2018-01-18 00:08:57",
"updatedBy": null,
"updatedAt": "2018-01-19 00:05:51"
}
]
}
]
}
您正在嘗試將您的 api 響應轉換為 CategoryInterface 數組,但情況並非如此,您最好像這樣使用您的訂閱方法:
.subscribe((response: any) => {
this.categories = <CategoryInterface[]> response.categories;
console.log(this.categories);
});
這是您需要轉換為 CategoryInterface[] 的 api 響應類別
獎勵:angular 樣式指南注意到您需要聲明類而不是接口,並且您不必在類名后綴 Interface,因此只需將 CategoryInterface 命名為 Category。
您收到錯誤是因為您將response
聲明為CategoryInterface[]
,但response.categories
實際上是CategoryInterface[]
。 response
只是數組的包裝器。 當打字稿轉換為 javascript 時,所有類型都會被去除,這就是它在運行時正常工作的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.