我是Angular和RXJS的新手-我正在尝试从rest api返回标准化数据,并在客户机上组装层次结构。我创建了这个堆栈闪电战,这是我试图实现的一个非常基本的版本:https://stackblitz.com/edit/angular-ffdbza
这些接口( ParentData、AssnData和ChildData )表示从该应用程序接口返回的JSON数据。Parent和Child接口是我希望在客户机上表示数据的方式(在实际的应用程序中,我将把这个新对象绑定到一个分层网格)。关键点是,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对象添加到正确的父对象中,但我在将子对象与每个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;
}发布于 2019-10-09 00:22:10
我有一个新的堆栈闪电战,它正在工作,但它似乎不是最优雅的代码: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"
}
]
}
]https://stackoverflow.com/questions/58278450
复制相似问题