从API设置Angular 2动态表单的值 [英] Setting Values From API for Angular 2 Dynamic Form

查看:77
本文介绍了从API设置Angular 2动态表单的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图开始在Angular 2中创建动态表单,并且正在使用Angular食谱中的设置

I am trying to get started with creating a dynamic form in Angular 2, and I am using the setup from the Angular cookbook here as my starting point. I didn't have any issues with their setup, which just hard codes the data in the service as apposed to an api call. My issue is that when I try to use an api call the values don't seem to get set correctly.

在Angular食谱中,他们将question.service.ts文件硬编码为:

In the Angular cookbook they have the question.service.ts file hard coded as:

getQuestions() {
let questions: QuestionBase<any>[] = [
  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 questions.sort((a, b) => a.order - b.order);
 }
}

然后从app.component.ts文件中,从构造函数中简单地将其调用为:

And then from the app.component.ts file its simply called from the constructor as:

 constructor(service: QuestionService) {
 this.questions = service.getQuestions();
 }

然后,哪个问题"在app.component.ts模板中绑定到该问题

Which "questions" then binds to this in the app.component.ts template

 <dynamic-form [questions]="questions"></dynamic-form> 

我对question.service.ts进行了更改,以进行api调用(由于无法在家中访问该api,因此目前正在从json文件中访问

I made changes to the question.service.ts to make an api call (now currently from a json file cause I don't have access to the api at home)

 getFirstQuestion() {
    return this._http.get(this.__questionJSONApiBaseUrl)
        .map(data => data.json())
        .do(data => console.log('All: ' + JSON.stringify(data)))
        .catch(this.handleError);
}

从app.component.ts中以

Which is called from the app.component.ts as

ngOnInit() {
    this.service.getFirstQuestion()
        .subscribe(data => {
            this.data = data;

            if (data.Type == 'TextBox') {
                let questions: QuestionBase<any>[] = [
                    new TextboxQuestion({
                        key: data.Title,
                        label: data.Text,
                        value: '',
                        required: true,                          
                        order: data.Id
                    })];
            }              
        }
        );
 }

如您所见,我在.subscribe()内设置了属性,但是它似乎无法正常工作,因为当它绑定到模板中的[questions]时,我得到一个无法读取属性'forEach'的未定义"错误,该错误来自问题控制.服务文件,该文件将问题转换为FormGroup.

As you see I set the properties inside of the .subscribe(), but it doesn't seem to be working correctly because when it binds to [questions] in the template I get a "Cannot read property 'forEach' of undefined" error which comes from the question-control.service file which transforms the question to a FormGroup.

我知道数据即将到来,因为我可以在if语句内设置一个警报,并从api调用中成功查看数据.我相信我的问题是[questions]在数据准备就绪之前就已绑定.有人可以告诉我一种更好的方法吗,或者请提供任何建议以解决我做错的事情?有没有一种方法可以首先在api中设置属性?

I know that the data is coming in because I can set an alert inside the if statement and see the data from the api call successfully. I believe my issue is that [questions] is binding before the data is ready. Can someone tell me a better way to do this or please provide any suggestions to what I'm doing wrong please? Is there a way I could set the properties in the api first?

推荐答案

正如@silentsod所指出的,这里的问题是您正在执行异步操作,并试图将其存储为问题.您需要处理异步.

The issue here, as @silentsod pointed out, is that you're doing an async operation and trying to store that as your questions. You need to handle the async.

您可以通过两种方式进行操作...或者,从组件类中进行:

You can go about this two ways...either, from the component class do:

service.getQuestions((questions) => this.questions = questions);

或者,您可以从模板中使用异步管道:

Or, you could, from the template, use the async pipe:

<dynamic-form [form]="questions | async"></dynamic-form>

async管道订阅可观察对象(在本例中为questions)并返回值.

这篇关于从API设置Angular 2动态表单的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆