Angular: HTTP 客户端转换树状数据结构
Angular: HTTP client converting a tree like data structure
我从服务器得到了以下结构(适当的JSON结构)
Orga1
| + Department1
| | + Role1
| | + Role2
| + Department2
| | + Role10
| | + Role11
Orga 2
| + DepartmentAB
| | + RoleAB1
...
我想在 Angular 中有一个对象,比如
export interface Organization {
name: string;
lstDeparments: Department [];
}
export interface Department {
name: string;
lstRoles: string [];
}
但不知何故我不知道如何在 Angular 中设置匹配界面。因为属性 name
是动态变化的(例如 Orga1
、Orga2
)并且属性列表也需要动态填充内容。
知道如何正确设置 interface
吗? (自动转换)
您对这种数据结构有特定的语法:
interface Payload {
[key: string]: Orga;
}
interface Orga {
[key: string]: Department;
}
interface Department {
[key: string]: Role;
}
如果你想要 Orgas 的列表,你必须迭代一个对象,而不是一个数组。
您可以使用 Object.keys
或更新的浏览器(或者如果您有 polyfill)执行此操作,Object.entries
:
const orgas = Object.keys(payload).map(key => payload[key]);
const orgas = Object.entries(payload).map(([key, value]) => value);
您还可以使用 generation function 到 Symbol.iterator
来遍历您的对象,但我认为这有点矫枉过正:
const payload = {
orga1: { name: 'orga 1' },
orga2: { name: 'orga 2' },
[Symbol.iterator]: function *() {
for (const key of Object.keys(this)) {
yield this[key];
}
}
};
for (const value of payload) {
console.log(value);
}
我从服务器得到了以下结构(适当的JSON结构)
Orga1
| + Department1
| | + Role1
| | + Role2
| + Department2
| | + Role10
| | + Role11
Orga 2
| + DepartmentAB
| | + RoleAB1
...
我想在 Angular 中有一个对象,比如
export interface Organization {
name: string;
lstDeparments: Department [];
}
export interface Department {
name: string;
lstRoles: string [];
}
但不知何故我不知道如何在 Angular 中设置匹配界面。因为属性 name
是动态变化的(例如 Orga1
、Orga2
)并且属性列表也需要动态填充内容。
知道如何正确设置 interface
吗? (自动转换)
您对这种数据结构有特定的语法:
interface Payload {
[key: string]: Orga;
}
interface Orga {
[key: string]: Department;
}
interface Department {
[key: string]: Role;
}
如果你想要 Orgas 的列表,你必须迭代一个对象,而不是一个数组。
您可以使用 Object.keys
或更新的浏览器(或者如果您有 polyfill)执行此操作,Object.entries
:
const orgas = Object.keys(payload).map(key => payload[key]);
const orgas = Object.entries(payload).map(([key, value]) => value);
您还可以使用 generation function 到 Symbol.iterator
来遍历您的对象,但我认为这有点矫枉过正:
const payload = {
orga1: { name: 'orga 1' },
orga2: { name: 'orga 2' },
[Symbol.iterator]: function *() {
for (const key of Object.keys(this)) {
yield this[key];
}
}
};
for (const value of payload) {
console.log(value);
}