简体   繁体   English

如何从 angular 7 的 API 响应中制作动态形式?

[英]how to make dynamic form from API response in angular 7?

I'm working on dynamic form in angular 7. I have followed the way which is mentioned on angular official website.我正在研究 angular 7 中的动态形式。我遵循了 angular 官方网站上提到的方式。 I successfully implemented that tutorial but my scenario is different.我成功实施了该教程,但我的场景不同。 what kind of input will be there in form and all its attribute will come from a API response表单中有什么样的输入,它的所有属性都将来自 API 响应

this is the function in service which brings my data.这是服务中的功能,它带来了我的数据。 Please note: On the basis of API data i will populate my questions array, for now i used dummy data just to make sure flow is working.请注意:根据 API 数据,我将填充我的问题数组,现在我使用虚拟数据只是为了确保流程正常工作。 this is how my question.service.ts looks like这就是我的 question.service.ts 的样子

public response : QuestionBase<any>[] =[];      
getQuestions(id) {
  this.http.get(this.url+'selectAllFieldDetails/'+id)
.pipe(map(
( response: Response) => {
    let data = response;
    console.log(data);


   let questions: QuestionBase<any>[] = [

      new DropdownQuestion({
        key: 'brave',
        label: 'Bravery Ratings',
        class:'form-control fis-form-control',
        formclass:'',
        options: [
          {key: 'solid',  value: 'Solid'},
          {key: 'great',  value: 'Great'},
          {key: 'good',   value: 'Good'},
          {key: 'unproven', value: 'Unproven'}
        ],
        required: true,
        order: 2
      }),

      new TextboxQuestion({
        key: 'process',
        label: 'Process name',
        value: 'IT ',
        class:'form-control fis-form-control',
        formclass:'',
        required: true,
        order: 1
      }),


    ];
    this.response =  questions.sort((a, b) => a.order - b.order);
   }
  ));
  console.log(this.response);
  return this.response;
}

But problem is function return before the API response and it return empty array.但问题是 API 响应之前的函数返回,它返回空数组。 This is the way i'm calling from create-ticket.component.ts这是我从 create-ticket.component.ts 调用的方式

ngOnInit() {
  this.questions = this.service.getQuestions(24);
  console.log(this.questions);
}

Somehow i tried to get the API response first and store it in some variable and then calling this function this.service.getQuestions(24);不知何故,我试图首先获取 API 响应并将其存储在某个变量中,然后调用此函数 this.service.getQuestions(24); but then it shows error that但随后它显示错误

Error: Cannot find control with name: 'process'
at _throwError (forms.js:1775)
at setUpControl (forms.js:1683)
at FormGroupDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.addControl (forms.js:4532)
at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl (forms.js:5030)
at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges (forms.js:4980)
at checkAndUpdateDirectiveInline (core.js:9239)
at checkAndUpdateNodeInline (core.js:10507)
at checkAndUpdateNode (core.js:10469)
at debugCheckAndUpdateNode (core.js:11102)
at debugCheckDirectivesFn (core.js:11062)

and Formgorup data remains empty.并且 Formgoup 数据保持为空。 Please help me in this problem.请帮我解决这个问题。 Thanks in advance提前致谢

So finally after a long r&d I have done this.因此,经过长时间的研发,我终于做到了。 basically there was two problem基本上有两个问题

  1. function in service respond before the API response服务中的函数在 API 响应之前响应
  2. form get created before the data come into business在数据进入业务之前创建表单

So for first issue i used the concept of async await feature in angular因此,对于第一个问题,我在 angular 中使用了async await功能的概念

In the create-ticket.component.ts we added async and await like this.在 create-ticket.component.ts 中,我们像这样添加了 async 和 await。

async ngOnInit() {
    this.questions = await this.service.getQuestionss(24);
    if(this.questions.length>0){
       this.showForm=true;
    }
}

and in service we return a promise在服务中,我们回报了一个承诺

async getQuestionss(id): Promise<any> {
     this.responses = await this.apiServce.getAllInputFields(id).toPromise();
}

it responds as a promise so it wait till the api response.它作为承诺响应,所以它等待 api 响应。 this.apiservice.getAllInputFields(id) is just a http api call from server. this.apiservice.getAllInputFields(id)只是来自服务器的 http api 调用。

For 2nd problem i used just a small solution.对于第二个问题,我只使用了一个小解决方案。 i added *ngIf in form so when the api respond with data then only form start to build.我在表单中添加了 *ngIf,所以当 api 用数据响应时,只有表单开始构建。

<app-dynamic-forms *ngIf="showForm" [questions]="questions"></app-dynamic-forms>

Thats all and problem resolved.就是这样,问题解决了。

outdated info based on stackblitz基于stackblitz的过时信息

You should should always subscribe to an async call in order for it to be executed您应该始终订阅异步调用以使其执行

ngOnInit() { this.questions = this.service.getQuestions(24).subscribe(result => { do something with result }, err => { something went wrong }); }

Here is a stackblitz, based on yours : https://stackblitz.com/edit/angular-h8zakj?embed=1&file=src/app/question.service.ts这是一个基于你的堆栈闪电战: https ://stackblitz.com/edit/angular-h8zakj?embed =1& file=src/app/question.service.ts

as I said there was an issue with your setTimeout.正如我所说,您的 setTimeout 存在问题。 the data was not accessible where you wanted it.数据无法在您想要的地方访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM