我是Angular和RXJS的新手,我试图从rest api返回规范化的数据并在客户端上组装层次结构。我创建了这个堆栈闪电战,这是我要完成的任务的一个非常基本的版本:https://stackblitz.com/edit/angular-ffdbza
这些接口(ParentData,AssnData和ChildData)表示从API返回的JSON数据。父接口和子接口是我希望数据在客户端上表示的方式(在真实应用程序中,我会将这个新对象绑定到分层网格)。关键在于,Assn数据具有一个属性(statusCode),该属性需要基于父级应用于每个子级。
// represents normalized data coming from the service
export interface ParentData {
parentCode: string,
name: string
}
export interface AssnData {
parentCode: string
childId: number,
statusCode: string
}
export interface ChildData {
childId: number,
type: string
}
// represents the merged data for display
export interface Parent {
parentCode: string,
name: string
kids: Child[]
}
export interface Child {
childId: number
type: string,
statusCode: string
}
这是我到目前为止的代码(从闪电战中的data.component.ts中获取)。它将Assn对象添加到正确的父对象中,但是我无法将Child对象与每个Assn对象合并。我正在做一个console.log以查看结果。
getRelationalData() {
let x = combineLatest(
this.parentData$,
this.assnData$,
this.childData$
).pipe(
map(([pData, aData, cData]) => {
return pData.map(p => {
return {
...p,
kids: aData.filter(a => a.parentCode === p.parentCode)
}
})
})
)
return x;
}
我有一个正在工作的新堆栈闪电战,但似乎不是最优雅的代码:https://stackblitz.com/edit/angular-rg6q5d?file=src/app/data.component.ts
我也更改了输出,以在屏幕上显示JSON之前/之后,以便更轻松地查看我要执行的操作(希望如此)。任何人都可以提供使它变得更好的见解吗?
getRelationalData() {
let x = combineLatest(
this.parentData$,
this.assnData$,
this.childData$
).pipe(
map(([pData, aData, cData]) => {
return pData.map(p => {
// get assn objects for this parent
let assn = aData.filter(a => a.parentCode === p.parentCode);
// get kids for this parent based on assn object (filter undefined)
let kids = cData.map(c => this.mergeData(c, assn))
.filter(k => k !== undefined ) ;
// return a new parent with the newly created child objects
return {
...p,
kids: kids
}
})
})
//, tap(x => console.log(x))
)
return x;
}
mergeData(child, assnObs){
// filter the assn objects for each child
let assn = assnObs.find(a => a.childId === child.id);
// return undefined so it can be filtered later
if (assn === undefined){
return assn;
}
//return the child object with the appropriate statusCode
return Object.assign(
{},
child,
{
statusCode: assn.statusCode
}
)
}
结果JSON-父对象和子对象正确相互关联,并且每个子对象都具有基于父对象的适当statusCode:
[
{
"parentCode": "abc",
"name": "John",
"kids": [
{
"id": "123",
"name": "Billy",
"age": "10",
"statusCode": "tallest"
},
{
"id": "789",
"name": "Sue",
"age": "6",
"statusCode": "youngest"
}
]
},
{
"parentCode": "xyz",
"name": "Jane",
"kids": [
{
"id": "456",
"name": "Bobby",
"age": "8",
"statusCode": "something"
},
{
"id": "789",
"name": "Sue",
"age": "6",
"statusCode": "whatever"
}
]
}
]