YPE 'Observable<QuestionBase<string>[]>'缺少以下属性



我有一个API,它以JSON文档的形式返回一些数据,可以有两个级别,一个是父级,然后一些父级可以有子级。目前,我正在阅读json文档,并使用forEach循环在数组中创建新对象。至于子项的i,请检查数组中是否有子项,如果有,请将其传递给另一个函数以解析子项,然后用新创建的Document设置父项。除了一件事之外,所有的似乎都能工作,当我试图对我的新对象数组进行排序时,我得到了一个错误

我使用的代码

buildChild(data : any){
let children : QuestionBase<string>[] = []
if( data.children &&  data.children.length > 0){
data.children.forEach(child => {
switch(child.type) { 
case 'TextboxQuestion': { 
children.push(new TextboxQuestion({
key: child.key,
label: child.label,
value: child.value,
placeholder: child.placeholder,
order: child.order,
required: child.required,
function: child.function,
class: child.class,
style: child.style,
childhidekey: child.childhidekey,
childhidevalue: child.childhidevalue
}))
break; 
}
case 'RadioButtonQuestion': { 
children.push(new RadioButtonQuestion({
key: child.key,
label: child.label,
value: child.value,
placeholder: child.placeholder,
order: child.order,
required: child.required,
function: child.function,
class: child.class,
style: child.style,
options: child.options,
childhidekey: child.childhidekey,
childhidevalue: child.childhidevalue
}))
break; 
}
case 'CheckboxQuestion': { 
this.questions.push(new CheckboxQuestion({
key: child.key,
label: child.label,
value: child.value,
placeholder: child.placeholder,
order: child.order,
required: child.required,
function: child.function,
class: child.class,
style: child.style,
options: child.options,
childhidekey: child.childhidekey,
childhidevalue: child.childhidevalue
}))
break; 
} 
}}
)
// return children
return of(children.sort((a, b) => a.order - b.order));
} }

错误为

键入'Observable<问题库[]>'缺少以下内容类型"QuestionBase[]"中的属性:长度、弹出、推送、,concat和25个以上。

此外,也许有比我的方法更好的方法来做到这一点,所以任何指针都是有用的,值得赞赏

Stackblitz样品

我浏览了您的stackblitz示例。问题出在buildChild()方法和question-base.ts

  1. 您的question-base.ts将其声明为children属性的类型:
style: string;
children?: QuestionBase<T>[]
childhidekey?: string;
  1. ,但您的buildChild方法返回一个可观察的:
// return children
return of(children.sort((a, b) => a.order - b.order));

要解决这个问题,只需从buildChild中删除of,瞧,它可以工作:

return children.sort((a, b) => a.order - b.order);

只需将JS对象来回转换为JSON即可删除所有对象函数。

children: JSON.parse(JSON.stringify(children))

这就是结果:stackblitz

最新更新