【问题标题】:Getting "Cannot read property 'geocodingForm' of undefined"获取“无法读取未定义的属性'geocodingForm'”
【发布时间】:2019-09-09 03:39:50
【问题描述】:

我正在使用来自 Angular Material 的反应形式。我正在尝试删除提到的错误。我可以在使用 console.log 提交时获取输入的值,但是当我试图将值放入 onSubmit 方法下的变量“地址”时,我一直遇到错误。

我已经尝试过以下方法:

  • var address=this.geocodingForm.get('input').value
  • var address=this.geocodingForm.value.input

以及将 var 更改为 let。

geocoding.component.html

    <mat-grid-tile colspan='60'>
        <div #gmap class="map"></div>
    </mat-grid-tile>

    <mat-grid-tile colspan='40'>
    <form novalidate [formGroup]="geocodingForm" #gform="ngForm" (ngSubmit)="onSubmit()">
      <h4>Geocoding Service</h4>
      <p>
        <input matInput formControlName="input" placeholder="address" type="text" required>
        <mat-error *ngIf="formErrors.input">{{formErrors.input}}</mat-error>
      </p>
      <button type="submit" mat-button class="background-primary text-floral-white" [disabled]="gform.form.invalid">Submit</button>
    </form>

    </mat-grid-tile>
</mat-grid-list>

geocoding.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-geocoding',
  templateUrl: './geocoding.component.html',
  styleUrls: ['./geocoding.component.css']
})
export class GeocodingComponent implements OnInit {

  geocodingForm: FormGroup;
  map: google.maps.Map;
  errMess: string;
  mapProp ={};
  @ViewChild('gform', { static: false }) geocodingFormDirective;
  @ViewChild('gmap') gmapElement: any;

  constructor(private fb: FormBuilder,//FormBuilders is an array of groups(i.e. Name, email, Address (new form group as address can be separated further like state, city, etc.))
  ) {
    this.createForm();
  }

  ngOnInit() {
    this.mapProp = {
      center: new google.maps.LatLng(18.5793, 73.8143),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    this.map = new google.maps.Map(this.gmapElement.nativeElement, this.mapProp);
  }

  formErrors = {
    'input': ''
  };

  validationMessages = {
    'input': {
      'required': 'Please provide an address'
    }
  };

  createForm() {
    this.geocodingForm = this.fb.group({
      input: ['', [Validators.required]]
    });

    this.geocodingForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now

  }

  onValueChanged(data?: any) { //data parameter is optional by use of "?"
    if (!this.geocodingForm) { return; }
    const form = this.geocodingForm;
    for (const field in this.formErrors) {
      if (this.formErrors.hasOwnProperty(field)) {
        // clear previous error message (if any)
        this.formErrors[field] = '';
        const control = form.get(field);
        if (control && control.dirty && !control.valid) {
          const messages = this.validationMessages[field];
          for (const key in control.errors) {
            if (control.errors.hasOwnProperty(key)) { //condition unnecessary?
              this.formErrors[field] += messages[key] + ' ';
            }
          }
        }
      }
    }
  }

   onSubmit() {

    console.log(this.geocodingForm.value.input);
    var geocoder = new google.maps.Geocoder();
    geocodeAddress(geocoder, this.mapProp);

    function geocodeAddress(geocoder, resultsMap) {
      var address=this.geocodingForm.get('input').value;

      geocoder.geocode({'address': this.address}, function(results, status) {
        if (status === 'OK') {
          resultsMap.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({
            map: resultsMap,
            position: results[0].geometry.location
          });
        } else {
          alert('Geocode was not successful for the following reason: ' + status);
        }
      });
    }


    this.geocodingFormDirective.resetForm();
    this.geocodingForm.reset({
      input: ''
    });
  }


}

我只是希望不会收到错误:

无法读取未定义的属性“geocodingForm”

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    这是因为您使用的是传统的function,其中this 的值取决于函数的调用方式。

    使用箭头函数代替

    geocodeAddress(geocoder, resultsMap){}
    

    &删除嵌套关键字function

    如果能去掉嵌套的function,在组件类中创建单独的函数就更好了

    【讨论】:

    • Use arrow function instead like ... 像什么?你还没有显示箭头函数
    • 分离功能在其他事情中起作用。虽然我可以使用一些更具体的解释来解释为什么会这样。
    • @JaromandaX - 我已经按照你的建议做了,除了使它比传统的更简单之外,我也不完全确定这部分箭头功能的好处。另外, const 不起作用,我不得不删除它
    • @Robby = 使用箭头函数不是我的想法,我只是指出 brk 代码不显示任何箭头函数
    猜你喜欢
    • 2020-02-14
    • 1970-01-01
    • 2020-12-05
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2021-07-08
    相关资源
    最近更新 更多