首页 > 解决方案 > 使用 JSON 数据创建的 Angular 动态表单

问题描述

亲爱的读者。我正在尝试使用已为红色的 Json 数据制作动态表单。动态表单基于 Angular 的示例,如下所示:https ://angular.io/guide/dynamic-form

我所做的编辑是我从外部 Json 文件中读取数据并尝试加载这些数据,而不是在链接中看到的文件“question.service.ts”中的硬编码文件。

这是我的 Json 文件的样子:

{
  "formInfo": {
    "name": "test"
  },
  "fields": [
    {
      "controlType": "textbox",
      "key": "firstName",
      "label": "Voornaam",
      "required": true,
      "value": "Mark",
      "order": 1
    },
    {
      "controlType": "textbox",
      "key": "surName",
      "label": "Achternaam",
      "required": true,
      "order": 2
    },
    {
      "controlType": "textbox",
      "key": "emailAddress",
      "label": "Email",
      "required": false,
      "order": 3
    },
    {
      "controlType": "dropdown",
      "key": "brave",
      "label": "Beoordeling",
      "required": "",
      "order": 4,
      "options": {
        "solid": "Solid",
        "great": "Great",
        "good": "Good",
        "unproven": "Unproven"
      }
    }
  ]
}

我检索数据并作为可观察返回的函数(in question.service.ts)如下所示:

getQuestions2() : Observable<QuestionBase<any>[]> {

let questions: QuestionBase<any>[] = [];

const exampleObservable = new Observable<QuestionBase<any>[]>((observer) => 
{
let url = "../assets/exampleData.json"
this.http.get(url).subscribe((data) => {

  for (let x of data['fields']){

    if (x.controlType == "textbox"){
        let textboxItem = new TextboxQuestion({
        key: x.key,
        label: x.label,
        value: x.value,
        order: x.order
      })
      questions.push(textboxItem);
    }

    else if (x.controlType == "dropdown"){

      let dropDownItem = new DropdownQuestion({
        key: x.key,
        label: x.label,
        value: x.value,
        options: x.options,
        order: x.order
      })
      questions.push(dropDownItem);

    }
  }
})
observer.next(questions.sort((a, b) => a.order - b.order));
})
return exampleObservable;
} 

将服务与前端连接起来的代码如下所示:

export class AppComponent implements OnInit {
   questions: any[];

   constructor(private service: QuestionService) {
   this.getaSyncData();
   //this.questions = this.service.getQuestions();
   //console.log(this.questions);
   }

   getaSyncData(){
   this.service.getQuestions2()
    .subscribe((data) => this.questions = data);
    console.log(this.questions);
   }

标签: jsonangularformsdynamicobservable

解决方案


我终于为那些将来会遇到类似问题的人解决了这个问题

即使我正确地从 JSON 文件中读取数据并在控制台中打印,我也无法将表单加载到 html 中。我在加载数据的 div 中添加了一个 *ngIf。在 Angular.io 的示例中,它位于 App.component.html 上的模板中。是的,就是这么简单。


推荐阅读