【问题标题】:Set Default Form Values from API Call通过 API 调用设置默认表单值
【发布时间】:2016-09-20 17:23:17
【问题描述】:

当我尝试在我的 ngOnInit 方法中启动表单控件值时出现以下错误:

错误

formGroup expects a FormGroup instance. Please pass one in.

方法

ngOnInit() {
    this.getBusinessData().then((response:any) => {
        this.businessForm = this.formBuilder.group({
            'business_name': [response.data.business_name, Validators.required],
            'email': [response.data.email, Validators.required]
        });
    });
}

在从我的 API 服务调用返回一个承诺后,我能够通过使用 setValue 来解决这个问题,并且它可以正常工作:

    ngOnInit() {
        // Build the form
        this.businessForm = this.formBuilder.group({
            'business_name' : ['', Validators.required],
            'email'   : ['', Validators.required],
        });
        // Fetch data for the view
        this.getBusinessData().then((response:any) => {
            this.businessForm.setValue({
                business_name: response.data.business.business_name,
                email: response.data.business.email
            });
        });
    }

但似乎不是最好的方法。我应该如何将 API 返回的数据绑定到表单控件?看来我不应该使用 formGroups 并且可能只使用 ngModels 将数据绑定到表单?

更新: 使用 micronyks 方法,我尝试了以下方法:

    ngOnInit() {
        // Bind data to the form
        this.getBusinessData().then((response:any) => {
            this.businessForm = this.formBuilder.group({
                'business_name' : [response.data.business.business_name==undefined?'': response.data.business.business_name, Validators.required],
                'email' : [response.data.business.email==undefined?'': response.data.business.email, Validators.required]
            });
        });
    }

但它在控制台中返回以下错误:

EXCEPTION: Uncaught (in promise): Error: Error in edit.template.html:12:10 caused by: formGroup expects a FormGroup instance. Please pass one in.

当它被包裹在 API 调用中时,这似乎会发生。 this 的值是否被覆盖?

【问题讨论】:

  • 有效吗?如果是这样,您只想知道最好的方法吗?
  • @micronyks 我的第二种方法有效,但我正在寻找更清洁的解决方案。我觉得必须有比在 formGroup 对象上运行 setValue 方法更好的方法。从我的 API 调用中解决承诺后,有没有办法在 formBuilder 构造函数中绑定数据?当我尝试时,我不断收到上述错误
  • 我以前没试过,但你可以试试这个:this.businessForm = this.formBuilder.group({ 'business_name' : [response.data.business.business_name==undefined?'':response.data.business.business_name, Validators.required], ... });
  • 我希望你明白我想说什么。现在您不需要使用setValue 方法。只需抓取承诺返回的数据并使用它,如上面的注释所示(您可以分配其抓取响应数据的自定义对象)。如果有效,请告诉我。
  • @micronyks 谢谢,请看我上面的更新!

标签: angular angular2-forms angular2-http


【解决方案1】:

您需要在 angular2 渲染视图之前设置 this.businessForm 实例。 解决方案_1:仅在设置 formBuilder 实例后使用 *ngIf 显示表单。 解决方案_2:将 formbuilder this.businessForm 设置为默认值,然后在收到 API 响应时更新您的表单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多