目前,这有效并且在运行时不会出现错误,但是我的文本编辑器给出了一个错误,指出类型'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"
}
]
}
]
}
答案 0 :(得分:1)
您正在尝试将您的api响应转换为CategoryInterface数组而不是这种情况,您最好使用这样的订阅方法:
.subscribe((response: any) => {
this.categories = <CategoryInterface[]> response.categories;
console.log(this.categories);
});
您的api响应类别需要转换为CategoryInterface []
Bonus:您需要声明类而不是接口的角度样式指南通知,并且您不必使用Interface为类名添加后缀,因此只需将CategoryInterface命名为Category。
答案 1 :(得分:0)
您收到错误是因为您将response
声明为CategoryInterface[]
,但response.categories
实际上是CategoryInterface[]
。 response
只是数组的包装器。当typescript转换为javascript时,所有类型都被删除,这就是它在运行时工作正常的原因。