我正在使用 Angular 呼叫外部 API。Json 資料的格式如下:
[
{
"AccessGroupsIdList": [],
"FirstName": "Greg",
"LastName": "Tipton",
"LocationIdList": [],
"PermissionProfile": {
"Name": "Agent",
"PermissionProfileId": {
"ID": "xy678219-bd7c-103d-b56b-1f1234a85990"
},
"Type": 3
},
"ManagerName": "Gilchrist, George",
"Status": true,
"UserGroupID": {
"ID": "00000000-0000-0000-0000-000000000000"
},
"UserGroupName": "ROOT",
"UserId": {
"ID": "4445cc66-819a-4da0-8fbf-d0bb8ce65941"
}
}
]
由于 json 資料是嵌套的,如何在打字稿中創建一個類來讀取它?
export class Employees
{
AccessGroupsIdList: string[];
FirstName: string;
LastName: string;
LocationIdList : number[];
PermissionProfile ??
ManagerName: string;
Status: boolean;
UserGroupID ??
UserGroupName : string;
UserId ??
}
請指導如果PermissionProfile, PermissionProfile 會單獨嵌套類嗎?我如何宣告這些?
uj5u.com熱心網友回復:
嘗試如下宣告 Typescript 類結構:
export class Employees
{
AccessGroupsIdList: string[];
FirstName: string;
LastName: string;
LocationIdList : number[];
PermissionProfile: PermissionProfile;
ManagerName: string;
Status: boolean;
UserGroupId: UserGroupID;
UserGroupName : string;
UserId: UserID;
}
export class PermissionProfile
{
name: string;
permissionProfileId: PermissionProfileID;
type: string;
}
export class PermissionProfileID
{
id: string;
}
export class UserGroupID
{
id: string;
}
export class UserID
{
id: string;
}
我建議使用 Id 來命名屬性名稱(例如 with UserGroupId)。該name和type在打字稿類屬性的名稱是有效的(不像在C#語法)。
uj5u.com熱心網友回復:
為了擴展 Andrew Halil 的回答,我將在您的定義中使用介面而不是類,因為似乎沒有涉及任何類方法;您只是在描述從服務器回傳的 JSON 物件的形狀
export interface Employee
{
AccessGroupsIdList: string[];
FirstName: string;
LastName: string;
LocationIdList : number[];
PermissionProfile: PermissionProfile;
ManagerName: string;
Status: boolean;
UserGroupId: ID;
UserGroupName : string;
UserId: ID;
}
export interface PermissionProfile
{
name: string;
permissionProfileId: ID;
type: string;
}
export interface ID
{
id: string;
}
現在至于實作,我并沒有那么多地使用 Angular,但是你會做這樣的事情來輸入專案
async function listEmployees(): Promise<Employee[]> {
// Make a fetch call to the API endpoint
const data = await fetch('https://some-api-endpoint.web/employees')
// if the response comes back ok, return the JSON-ified response.
.then(res => {
if(res.ok) return res.json()
return [];
});
// Instruct typescript that "data" is to be treated as an array of Employee elements.
return data as Employee[]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/325939.html
