Angular Dynamic Forms-通过http.get请求添加远程源



我目前正在处理一个动态表单项目,我使用了以下代码作为起点-构建开箱即用的动态表单。

然而,当我想要基于传入的JSON动态创建表单字段时,我似乎遇到了一个问题

我知道当我使用http.get((时,它会返回一个可观察的,但动态表单代码中的变量也是一个可观测的const questions: QuestionBase<string>[],所以我需要如何映射它?

下面的代码来自问题服务,因为它是硬编码的:

getQuestions() {
const questions: QuestionBase<string>[] = [
new DropdownQuestion({
key: 'brave',
label: 'Bravery Rating',
options: [
{key: 'solid',  value: 'Solid'},
{key: 'great',  value: 'Great'},
{key: 'good',   value: 'Good'},
{key: 'unproven', value: 'Unproven'}
],
order: 3
}),
new TextboxQuestion({
key: 'firstName',
label: 'First name',
value: 'Bombasto',
required: true,
order: 1
}),
new TextboxQuestion({
key: 'emailAddress',
label: 'Email',
type: 'email',
order: 2
})
];
return of(questions.sort((a, b) => a.order - b.order)); }

这是我动态创建表单字段的代码:

getQuestions(id:any) {
const questions: QuestionBase<string>[] = [];
// Dynamically create form fields
this.dataService.loaddatafromJSON() // This is just an http.get request
.subscribe((response) => {
if (response != null)
{
var form = response.forms.filter(x => x.id === id); // Get form from custom object array
var fields = form.fields; // Get all fields from Form e.g. textbox, textarea etc...
for (var field of fields) { // Interate through form fields
if (field.type === "textbox")
{
// Found Textbox field, add to question array and so on...
questions.push(
new TextboxQuestion({
key: 'id',
label: 'label',
value: '',
required: true,
placeholder: 'placeholder',
order: 1
})
);
}
}
}
});
// ------------------------------
return of(questions.sort((a, b) => a.order - b.order)); }

当我运行代码时,我得到以下错误:

ERROR Error: Cannot find control with name: 'id'
at _throwError (forms.js:2431)
at setUpControl (forms.js:2337)
at FormGroupDirective.addControl (forms.js:5475)
at FormControlName._setUpControl (forms.js:6057)
at FormControlName.ngOnChanges (forms.js:5988)
at FormControlName.rememberChangeHistoryAndInvokeOnChangesHook (core.js:2131)
at callHook (core.js:3042)
at callHooks (core.js:3008)
at executeInitAndCheckHooks (core.js:2960)
at refreshView (core.js:7187)

任何帮助都将不胜感激,我只想能够重建问题数组并返回。

感谢

我在dynamic-form.component.ts:中找到了答案

ngOnInit() {
//this.form = this.qcs.toFormGroup(this.questions);
}
ngOnChanges() {
this.form = this.qcs.toFormGroup(this.questions);
}

我可能对此描述不好,因为我也是新手,但我也遇到了同样的问题。Angular教程中的方法getQuestions(((上面的第一个片段(通过最后一行返回Observable

'return of(...)'.

如果您希望此函数从服务器查询返回数据,那么您需要确保您的方法仍然返回Observable。它可能看起来有点像。。。很抱歉没有考虑到你的例子,但你可能明白了。。。您返回一个http请求(但未订阅(

getQuestions() {
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
const url = 'http://...';
const body = ...;
return this.http.post<any>(url, body, httpOptions)
.pipe(
map(dataRaw => this.createQuestions(dataRaw))
);
}

createQuestions(dataRaw: any) {
let questions: QuestionBase<string>[] = [];
dataRaw.forEach(question=> {
questions.push(new TextboxQuestion(question));
});
return questions;
}

最新更新