我想在formArray中显示初始数据,我可以设置值并在控制台日志中显示值,但不以ui形式显示此数据
ngOnInit() {
this.getCertificate(this.id);
this.assessmentForm = this.fb.group({
certificateArray: this.fb.array([ this.createItem() ]),
});
}
createItem(): FormGroup {
return this.fb.group({
confirm: '',
score: '',
description: ''
});
}
getCertificate(id) {
this.certificateList = [];
this.UsersRegisterService.getCertificate(id).subscribe((res: any[]) => {
this.certificateList = res;
var index=0;
this.certificateList.forEach(element => {
this.AssessmentService.getCertificateAssessment(element.id.value).subscribe((res: any[]) => {
if(res!=null){
this.certificateArray.at(index).setValue(
{ confirm: res['confirm'], score: res['score']['value'],description:res['description']});
console.log( this.assessmentForm['controls'].certificateArray['controls'][index]['controls'].score.value);
}
});
index++;
});
});
}
我用这种方法设置值
this.certificateArray.at(index).setValue(
{ confirm: res['confirm'], score: res['score']})
请帮助我如何在Ui表单中显示此值
您可以稍微重构一下代码,现在您有了一个阴影名称res
。我会记录每个呼叫的响应,getCertificateAssessment
以确保您得到了期望的结果:
getCertificate(id) {
this.certificateList = []; // this should be set at the top of your component
this.UsersRegisterService.getCertificate(id).pipe(
catchError(err => {
console.log('get cert error', err);
return [];
})
).subscribe((list) => {
this.certificateList = list;
this.certificateList.forEach((element, i) => {
this.AssessmentService.getCertificateAssessment(element.id.value).pipe(
catchError(err => {
console.log('get assessment error', err);
return null;
})
).subscribe((res) => {
if (res) {
console.log('res', i, res); // be sure of response
this.certificateArray.at(i).setValue({
confirm: res.confirm,
score: res.score.value,
description: res.description
});
} else {
console.log('no res!');
}
});
});
});
}
克里斯在管道方面提出了一个很好的观点,但是我猜这些服务调用是http请求,因此它们就像一个承诺一样完成了。
我还添加catchError
了服务调用来捕获错误。
另外,您必须为每次评估打电话,这需要打电话。也许重构您的后端使其成为1个电话?
如果将端点重构为getCertficateAssessment
接受值数组并返回响应数组,则可以执行以下操作:
this.UsersRegisterService.getCertificate(id).pipe(
switchMap(list => this.AssessmentService.getCertificateAssessment(list.map(l => l.id.value)))
);
您需要为每个评估创建一个ID,以便分配它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句