开发者问题收集

错误 TypeError:无法读取未定义的属性“forEach”

2018-02-02
7148

我正在做一个项目,我想显示和编辑一个数组。我的问题是“无法读取未定义的属性‘forEach’”,我不明白为什么。

我的 component.html

<form [formGroup]="editHomeboxPForm" (ngSubmit)="onEditHomeboxP()" class="col s12" materialize>

           <div class="row">
               <div class="input-field col s10">
                 <div formArrayName="sensors_id">
                   <div class="form-group" *ngFor="let sensor of editHomeboxPForm.get('sensors_id').value; let i = index">
                     <br>
                     <select formControlName="{{i}}" id="sensors_id" materialize="material_select"
     [materializeSelectOptions]="homeboxp.sensors" [ngClass]="{invalid:
     invalidinput}">
                       <option value="" disabled selected>Select Sensor</option>
                       <option *ngFor="let sensor of homeboxp.sensors" [value]="sensor.sensors_id">{{sensor.sensor_serial}}</option>
                     </select>
                     <div class="button-left">
                       <button *ngIf="editHomeboxPForm.controls.sensors_id.value.length > 1" type="button" class="fa"
     (click)="onRemoveItem(i)">RemoveSensor</button>
                     </div>
                   </div>
                 </div>

               </div>
               <div class="input-field col s2">
               <button type="button" class="btn" (click)="onAddItem()">AddSensor</button>
               </div>
          </div>
</form>

Component.ts

  editHomeboxPForm: FormGroup;
  homeboxp: HomeboxP;

  constructor(private hps: HomeboxpackageService,
    private router: Router,
    private fb: FormBuilder,
    private activatedRoute: ActivatedRoute) {

      this.editHomeboxPForm = new FormGroup({
      'serial_number': new FormControl('', [Validators.required, Validators.nullValidator]),
      'sensors_id': this.fb.array([]) 
    });
  }

  ngOnInit() {
    this.populateFormHomeboxP();

  }
  ngAfterViewChecked() {

    Materialize.updateTextFields();
  }
  populateFormHomeboxP() {
    this.activatedRoute.params.subscribe(
      params => {
        this.hps.getHomeboxPById(params['id']).subscribe(
          homeboxp => {
            this.homeboxp = homeboxp;
            this.editHomeboxPForm.controls['serial_number'].setValue(homeboxp.serial_number);
            this.editHomeboxPForm.controls['sensors_id'].setValue(homeboxp.sensors_id); // at SafeSubscriber.eval [as _next]
           }
        );
      }
    );
  }
  onEditHomeboxP() {
    this.loading = true;
    let editHomeboxP = new HomeboxP(
      this.editHomeboxPForm.value
    );
    editHomeboxP.homebox_id = this.homeboxp.homebox_id;
    this.hps.UpdateHomeboxp(editHomeboxP).subscribe(
      result => {
        if (result === true) {
          Materialize.toast('successfully', 4000);
                 } else {
          this.loading = false;
        }
      },
      error => {
        this.loading = false;
      }
    );
  }
  onAddItem() {
    (<FormArray>this.editHomeboxPForm.controls['sensors_id']).push(new FormControl('', Validators.required));
   }
   onRemoveItem(index: number) {
    (<FormArray>this.editHomeboxPForm.controls['sensors_id']).removeAt(index);
 }

你能告诉我,问题出在哪里吗?在控制台中:ERROR TypeError:无法读取未定义的属性‘forEach’。控制台中还显示所有 json。像这样:

{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "sensors": [ {"sensor_serial":"SensorSerial1", "sensors_id":"11E807676E3F30B5"}, {"sensor_serial":"sensorserial2", "sensors_id":"11E807679D82841L"}, {"sensor_serial":"sensorserial3", "sensors_id":"11E80767A5CD2820"} ] ,"homeboxpackage_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J", "date_created":"2018-02-01T15:55:54.000Z", "date_modified":null, "serial_number":"serialn1", "user_id":"3"} }

1个回答

从我查看模板所收集的信息来看, homeboxp 变量中的数据实际上是您响应中的数组 sensors 。您需要迭代数组 sensors ,并从该数组中的每个对象将 sensor_id 推送到 formarray:

// iterate array, grab the sensor.id and push it to form array
this.homeboxp.sensors.forEach(x => {
  (this.editHomeboxPForm.get('sensors_id') as FormArray)
    .push(new FormControl(x.sensors_id))
})

DEMO

AVJT82
2018-02-02