[英]How to create an interface for object and array of objects in Angular 8 and type script?
I'm trying to create an interface for Object, objects, and array of objects.我正在尝试为对象、对象和对象数组创建一个接口。
Sample interface示例界面
export interface ErateColumn {
categories:{
[key:string]:column[]
}
}
interface column {
label:string
value:string
}
Sample API response like this像这样的示例 API 响应
{
"categories": {
"Basic Information": [
{ label: "Applicant Type", value: "ApplicantType" },
{ label: "Organization Name", value: "OrganizationName" },
],
"FRN Lineitem": [
{ label: "Monthly_Cost", value: "Monthly_Cost" },
],
"FRN status": [
{ label: "Purpose Type", value: "PurposeType" },
]
}
}
what you have provided in this._erateColumn.next(columnList)
method is columnList
.您在this._erateColumn.next(columnList)
方法中提供的是columnList
。 And somehow columnList
seems to be a single object of the interface ErateColumn, While your BehaviorSubject has type array of ErateColumn.不知何故, columnList
似乎是接口 ErateColumn 的单个对象,而您的 BehaviorSubject 具有 ErateColumn 类型数组。 Change that to ErateColumn or provide array in this._erateColumn.next(columnList)
method for your code to work.将其更改为 ErateColumn 或在this._erateColumn.next(columnList)
方法中提供数组以使您的代码工作。
EDIT编辑
According to the new screenshot of yours, it says property categories
is missing so either make it optional like this根据您的新屏幕截图,它说缺少属性categories
,因此可以像这样将其设为可选
export interface ErateColumn {
categories?:{
[key:string]:column[]
}
}
interface column {
label:string
value:string
}
or provide categories.或提供类别。
May be this approach can help someone可能这种方法可以帮助某人
You can convert JSON to typescript's class or interface , Using online tool json2ts or if you are using vs code (Visual Studio) use this extension QuickType - Paste JSON as Code您可以将JSON转换为 typescript 的类或接口,使用在线工具json2ts或者如果您使用的是vs 代码(Visual Studio),请使用此扩展QuickType - Paste JSON as Code
Note: Your JSON should be a valid JSON otherwise you will get errors注意:你的 JSON 应该是一个有效的 JSON 否则你会得到错误
Hope this helps...希望这可以帮助...
interface User {
name: string;
phone: string;
}
const user: User ==> Object
const usersList: User[] ===> Array of Objects
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.