【问题标题】:Can not read property get of undefined Ionic 3无法读取未定义 Ionic 3 的属性获取
【发布时间】:2019-07-31 05:45:57
【问题描述】:

我们正在尝试在 ionic 3 中构建一个设置表单,但它会定期抛出不同的错误。作为主要问题,它显示无法读取未定义的属性获取。我们正在使用 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 却不行。什么会导致这些问题?代码有什么问题?

【问题讨论】:

  • 你能分享你的完整代码,包括构造函数吗?
  • @SergeyRudenko 我刚刚包含它。

标签: typescript ionic-framework ionic3 angular6


【解决方案1】:

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

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

【讨论】:

  • @NewTechLover 确保你得到.get(...) 的所有出现。您的错误指向它们的父对象为空。否则,请发布完整的错误消息。绝对不是打字稿问题
【解决方案2】:

在我看来,您的代码在初始化和使用表单的方式上有点不合常规。至少我曾经看到过更接近 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 init 移动到构造函数中,而不是您现在使用的生命周期挂钩。

【讨论】:

  • 我按照你说的做了所有的改变。它抛出无法读取未定义的属性控件
  • 添加更改后能否分享完整的 ts 文件
猜你喜欢
  • 2019-01-27
  • 2019-11-11
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 2019-01-05
  • 2015-04-25
  • 1970-01-01
  • 2020-02-14
相关资源
最近更新 更多