【问题标题】:Ionic 2 - Setting value of a model driven formIonic 2 - 模型驱动形式的设置值
【发布时间】:2017-04-29 16:37:50
【问题描述】:

当我想在加载此表单时将以前保存的值从本地存储中归因于此表单时,我遇到了与 Ionic 2 中内置的模型驱动表单相关的问题。

我设法使用 Ionic 的存储服务保存了它,但是我未能将此保存的数据归因于表单。我收到以下错误:

TypeError: 设置一个只有 getter 的属性

这是我的代码,到目前为止:

import { Component } from '@angular/core';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
import { NavController, NavParams } from 'ionic-angular';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'page-survey',
  templateUrl: 'survey.html',
  providers: [Storage]
})

export class Survey {
  form: FormGroup;
  networkStatus: boolean = true;

  constructor(public navCtrl: NavController, public navParams: NavParams,
              public formBuilder: FormBuilder, private storage: Storage) {

    // localstorage 
    this.storage = storage;

    this.form = formBuilder.group({
      "isPropertyOwner": ["", Validators.required],
      "familyMembers": ["", Validators.compose([Validators.required, Validators.minLength(0)])],
      "ownsProperty": ["", Validators.required],
      "pragueIdentify": ["", Validators.required],
      "pesticidesUsage": ["", Validators.required],
      "propertyLevel": ["", Validators.required]
    });

    /* Check if form has been changed */
   this.form.valueChanges.subscribe(data => 
      this.storage.set('survey', data)
    );
  }

  ngAfterViewInit() {
    // checking if there's something saved, then...
    if(this.storage.get('survey')) {
      this.storage.get('survey').then((data) => {
        console.log('This is ', data);
        this.form.value = data;
      });
    }
  }

  onSubmit(form) {
    console.log(form);
    this.storage.clear().then(() => {
      console.log('Keys have been cleared');
    });

  }
}

如何将保存的值归因于此表单?

【问题讨论】:

    标签: angular local-storage ionic2 angular2-forms


    【解决方案1】:

    FormGroup 的属性value 是只读属性,这意味着您不能直接对其进行编辑。您需要使用get() 函数获取每个FormControl,然后使用setValue() 函数更改其值。无论如何,而不是这个:

    this.form.value = data;
    

    你需要使用这个:

    this.form.get('isPropertyOwner').setValue(data.isPropertyOwner);
    this.form.get('familyMembers').setValue(data.familyMembers);
    this.form.get('ownsProperty').setValue(data.ownsProperty);
    this.form.get('pragueIdentify').setValue(data.pragueIdentify);
    this.form.get('pesticidesUsage').setValue(data.pesticidesUsage);
    this.form.get('propertyLevel').setValue(data.propertyLevel);
    

    【讨论】:

    • 这按预期工作!非常感谢,Хвала вам @StefanSvkota
    【解决方案2】:

    我认为您必须在从 constructor 中删除以下两行后进行检查,因为您已经将 private storage: Storage 声明为 constructor 参数。

    // localstorage 
    this.storage = storage;
    

    【讨论】:

    • 同样的错误。我认为这不是问题,因为我没有存储或检索存储值的问题。我可以通过控制台看到该值已正确存储,但是我无法设置它。
    猜你喜欢
    • 1970-01-01
    • 2016-08-16
    • 2018-05-27
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 2017-08-05
    • 2017-02-02
    • 1970-01-01
    相关资源
    最近更新 更多