使用JSON数据创建的角动态表单

时间:2018-10-23 12:52:03

标签: json angular forms dynamic observable

尊敬的读者。我正在尝试使用红色的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"
      }
    }
  ]
}

我用于检索数据并以可观察的方式返回的函数(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);
   }

1 个答案:

答案 0 :(得分:0)

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

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