无法读取未定义的离子3的属性获取

时间:2019-03-09 09:44:00

标签: typescript ionic-framework ionic3 angular6

我们正在尝试在ionic 3中建立一个设置表单,但是它会定期抛出不同的错误。作为主要问题,它显示无法读取未定义的属性get。我们正在使用Ionic 3,这是该页面的代码:

  import {  FormBuilder, FormGroup, Validators, ValidatorFn, ValidationErrors } from '@angular/forms';

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        private fb: FormBuilder,
        private alertCtrl: AlertController,
        private tokenProvider: TokenProvider,
        private usersProvider: UsersProvider
      ) {
        this.tabElement = document.querySelector('.tabbar.show-tabbar');
        this.socket = io('http://localhost:3000');

      }
           ionViewDidLoad() {
                 this.user = this.tokenProvider.GetPayload();
            this.buildSettingsForm();
            if (this.user) {
              this.GetUser(this.user);
            }

            this.socket.on('refreshPage', () => {
              this.GetUser(this.user);
            });
            this.socket.on('refreshPage', () => {
              this.GetUser(this.user);
            });

          }


              GetUser(id) {
                this.usersProvider.GetUserById(id).subscribe(data => {
                  this.user = data.result;

                });
              }
              onSubmit() {
                this.SettingsForm.reset();
              }
              ionViewWillEnter() {
                (this.tabElement as HTMLElement).style.display = 'none';
              }
              ionViewWillLeave() {
                (this.tabElement as HTMLElement).style.display = 'flex';
              }
            ...
              private populateForm() {
                const unusedFields = [
                  '_id',
                  '__v',
                  'username',
                  'email',
                ];

                const userInfo = Object.assign({}, this.user);
                unusedFields.forEach((field) => delete userInfo[field]);
                this.SettingsForm.setValue(userInfo);
              }

              private buildSettingsForm() {
                this.SettingsForm = this.fb.group({
                  city: [null, [Validators.required, Validators.pattern('[a-zA-Z ]*')]],
                  country: [null, [Validators.required, Validators.pattern('[a-zA-Z ]*')]],
                  firstName: [null, [Validators.required, Validators.pattern('[a-zA-Z ]*')]],
                  lastName: [null, [Validators.required, Validators.pattern('[a-zA-Z ]*')]],
                });
                this.SettingsForm.setValidators(this.minimumAge(18));
              }

              UpdateUser() {
                this.usersProvider.EditUser(this.SettingsForm.value).subscribe(
                  data => {
                  },
                  err => console.log(err)
                );
            }

            }

这也是HTML。

<ion-content padding>
  <form [formGroup]="SettingsForm" (ngSubmit)="UpdateUser()">
    <ion-list style="margin-top: 15% !important" class="scroll">
      <ion-item>
          <ion-input class="input-field" formControlName="firstName" name="firstName" type="text" placeholder="First Name"></ion-input>
        </ion-item>
   <div *ngIf="!SettingsForm.get('firstName').valid && SettingsForm.get('firstName').touched"
    class="help-block">Please choose the gender</div>
      <ion-item>
        <ion-input class="input-field" formControlName="lastName" name="last name" type="text" placeholder="Last name"></ion-input>
      </ion-item>
   <div *ngIf="!SettingsForm.get('lastName').valid && SettingsForm.get('lastName').touched"
    class="help-block">Please choose the gender</div>
        <ion-item>
...
...
  <button ion-button block class="login-button">Sign Up</button>                
    </ion-list>
  </form>

它在控制台中的每个输入字段行上显示错误。问题可以在TS内部吗?因为当我使用另一种简单的形式进行测试时,它可以工作,但使用此TS则不能。什么会导致此类问题?代码有什么问题?

2 个答案:

答案 0 :(得分:0)

您在模板中使用的表单将在启动时未定义。使用Elvis运算符可避免模板中出现空异常:

<div *ngIf="!SettingsForm?.get('firstName')?.valid && SettingsForm?.get('firstName')?.touched"

答案 1 :(得分:0)

在我看来,您的代码在初始化和使用表单的方式上有点不合常规。至少我以前看过的角度更接近angular.io指南或Josh在本教程中找到的内容:https://www.joshmorony.com/advanced-forms-validation-in-ionic-2/

由于您的问题,该错误基本上显示“获取未定义”,这意味着* ngIf表达式中的SettingsForm有时是...未定义。

尝试使用以下方法代替get方法:

*ngIf="!SettingsForm.controls.lastName.valid && SettingsForm.controls.lastName.touched"

现在要避免在启动时对其进行定义-将formBuilder初始化移到构造函数中,而不是现在使用的生命周期挂钩。