New Reactive forms users. TypeError: Cannot read property 'firstName' of undefined

New Reactive forms users. TypeError: Cannot read property 'firstName' of undefined

我得到

TypeError: Cannot read property 'firstName'

当我加载我的 Reactive Form 时。表单行为似乎是正确的。我的数据正在填充到表单中,但我仍然收到此错误。

我查看了之前关于此的问题,但答案似乎不适用于我的具体情况。

这是我的 UserComponent:

export class UserComponent implements OnInit, OnDestroy {
  user: User;
  userId: string;
  userChangedSub = new Subscription();
  form: FormGroup;

  constructor(private userService: UserService) {

  }

  ngOnInit() {
    console.log('ngOnInit started');
    this.userId = this.userService.getUserId();
    this.userChangedSub = this.userService.getUser(this.userId).subscribe(user => {
      console.log('email is: ' + user.email);
      this.user = user;
      console.log(this.user);
    });
    this.form = this.createFormGroup();
  }

  createFormGroup() {
    return new FormGroup({
      first: new FormControl('', {validators: Validators.required}),
      last: new FormControl('', {validators: Validators.required})
    });
  }

  onSubmit() {
  }

  ngOnDestroy() {
    this.userChangedSub.unsubscribe();
  }
}

这是我的表格:

<section class="user-form">
  <form fxLayout="column" fxLayoutAlign="center center" [formGroup]="form" (ngSubmit)="onSubmit()">
    <mat-form-field>
      <input matInput type="text" *ngIf="user.firstName!==undefined" [value]="user.firstName" formControlName="first">
    </mat-form-field>
    <mat-form-field>
      <input matInput type="text" [value]="user.lastName" formControlName="last">
    </mat-form-field>
    <button type="submit" [disabled]="!form.valid"></button>
  </form>
</section>

表单显示了登录用户的正确名字和姓氏,但我仍然收到此错误。 我检查了表单是否 user.firstName 未定义。我认为这会删除 TypeError.

加载组件时,userundefined,这就是您收到错误的原因。您可以通过几种方式解决此问题。要么将 user: User; 更新为 user: User = {}; 之类的内容,要么更新您的 HTML 以包含这些 'null/undefined' 检查,如下所示:<input matInput type="text" *ngIf="user?.firstName!==undefined" [value]="user?.firstName" formControlName="first">