【问题标题】:Angular - ERROR TypeError: Cannot read properties of undefined (reading 'licence_number')Angular - 错误类型错误:无法读取未定义的属性(读取'licence_number')
【发布时间】:2021-11-05 12:05:58
【问题描述】:

在我的 Angular-12 中,我有以下代码:

而且您的 JSON 无效。应该是这样的:

{
  "message": "Employee Detail.",
  "error": false,
  "code": 200,
  "results": {
    "employee": {
      "id": 8,
      "first_name": "JONAH",
      "last_name": "YAKUBU",
      "other_name": "STANLEY",
      "licences": [
        {
          "id": 1,
          "licence_number": "dsdsdsd"
        }
      ]
    }
  }
}

界面:

export class EmployeeResponse {
  results!: { employee: IEmployee };
}

export interface IEmployee {
  id?: number;
  first_name: string;
  other_name: string;
  last_name: string;
  licence_number?: string;
  licences?: ILicence[];
}

export interface ILicence {
  id: number;
  licence_number: string;
  dl_classification_id: number;
  licenceclass?: {id:number,class_name:string};
}

服务:

  getEmployeeById(id: number): Observable<EmployeeResponse> {
    return this.http.get('/assets/data.json').pipe(
      map((response: any) => {
        if (!response) return response;

        if (!response.results) return response;

        if (!response.results.employee) return response;

        let employee: IEmployee = {
          ...response.results.employee,
          licence_number:
            response.results.employee.licences &&
            response.results.employee.licences[0].licence_number
        };

        response.results.employee = employee;

        return response;
      })
    );
  }

组件:

export class AppComponent {
  profileInfoForm!: FormGroup;
  licenceInfoForm!: FormGroup;

  profileTemplate: boolean = true;
  licenceTemplate: boolean = false;

  isLoading = false;
  employee: IEmployee;
  _id = 1;

  constructor(
    private fb: FormBuilder,
    private employeeService: EmployeeService
  ) {}

  ngOnInit(): void {
    this.isLoading = true;
    //this._id = this.route.snapshot.params['id'];
    this.updateEmployee();
    this.updateLicence();
    this.loadEmployeeById();
  }

  profileFunction() {
    this.profileTemplate = true;
    this.licenceTemplate = false;
  }

  licenceFunction() {
    this.profileTemplate = false;
    this.licenceTemplate = true;
  }

  updateEmployee() {
    this.profileInfoForm = this.fb.group({
      id: [''],
      first_name: [
        '', [Validators.required, Validators.minLength(2), Validators.maxLength(50)]
      ],
      other_name: ['', [Validators.maxLength(50)]],
      last_name: [
        '', [Validators.required, Validators.minLength(2), Validators.maxLength(50)]
      ]
    });
  }

  updateLicence() {
    this.licenceInfoForm = this.fb.group({
      id: [''],
      licence_number: ['', [Validators.required, Validators.minLength(2)]]
    });
  }

  get fp() {
    return this.profileInfoForm.controls;
  }
  get fl() {
    return this.licenceInfoForm.controls;
  }

  profileValidate() {
    if (!this.profileInfoForm.valid) {
      this.profileInfoForm.markAllAsTouched();
      return;
    }
  }

  licenceValidate() {
    if (!this.licenceInfoForm.valid) {
      this.licenceInfoForm.markAllAsTouched();
      return;
    }
  }

  loadEmployeeById() {
    this.employeeService
      .getEmployeeById(this._id)
      .subscribe((data: EmployeeResponse) => {
        console.log(data.results.employee)
        this.employee = data.results.employee;
        this.profileInfoForm.patchValue({
          first_name: this.employee.first_name,
          other_name: this.employee.other_name,
          last_name: this.employee.last_name
        });
        this.licenceInfoForm.patchValue({
          licence_number: this.employee.licence_number
        });
      });
  }
}
<div class="col-md-3">
  <div class="sticky-top mb-3">
    <div class="card">
      <div class="card-header">
        <h4 class="card-title">Click to Edit</h4>
      </div>
      <div class="card-body">
        <div id="external-events">
          <button (click)="profileFunction()" type="button" class="btn btn-block btn-primary">Profile</button>
          <button (click)="licenceFunction()" type="button" class="btn btn-block btn-warning">Licence</button>
        </div>
      </div>
      <div class="card-header">
      </div>

    </div>
  </div>
</div>

<div class="col-md-9" *ngIf="employee != undefined">
  <div *ngIf="profileTemplate" class="card card-default color-palette-box">
    <div class="card-body">
      <form [formGroup]="profileInfoForm" (ngSubmit)="onSubmitProfile()">
        <div class="row">
          <div class="col-md-12">
            <div class="row">
              <div class="col-12 col-md-4">
                <div class="form-group">
                  <label for="first_name">First Name:<span style="color:red;">*</span></label>
                  <input type="text" formControlName="first_name" placeholder="First Name" class="form-control" required/>
                </div>
                <div *ngIf="fp.first_name.touched && fp.first_name.invalid">
                  <div *ngIf="fp.first_name.hasError('required')">
                    <div class="text-danger">
                      First Name is required!
                    </div>
                  </div>
                  <div *ngIf="fp.first_name.hasError('minlength')">
                    <div class="text-danger">
                      First Name cannot be less than 2 characters!
                    </div>
                  </div>
                  <div *ngIf="fp.first_name.hasError('maxlength')">
                    <div class="text-danger">
                      First Name cannot be more than 50 characters!
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-4">
                <div class="form-group">
                  <label for="other_name">Middle Name:<span style="color:red;">*</span></label>
                  <input type="text" formControlName="other_name" placeholder="Middle Name" class="form-control" required/>
                </div>
                <div *ngIf="fp.other_name.touched && fp.other_name.invalid">
                  <div *ngIf="fp.other_name.hasError('maxlength')">
                    <div class="text-danger">
                      Middle Name cannot be more than 50 characters!
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-4">
                <div class="form-group">
                  <label for="last_name">Last Name:<span style="color:red;">*</span></label>
                  <input type="text" formControlName="last_name" placeholder="Last Name" class="form-control" required/>
                </div>
                <div *ngIf="fp.last_name.touched && fp.last_name.invalid">
                  <div *ngIf="fp.last_name.hasError('required')">
                    <div class="text-danger">
                      Last Name is required!
                    </div>
                  </div>
                  <div *ngIf="fp.last_name.hasError('minlength')">
                    <div class="text-danger">
                      Last Name cannot be less than 2 characters!
                    </div>
                  </div>
                  <div *ngIf="fp.last_name.hasError('maxlength')">
                    <div class="text-danger">
                      Last Name cannot be more than 50 characters!
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="card-footer">
          <button type="submit" class="btn btn-success" [disabled]="isLoading" class="btn btn-success" (click)="profileValidate()">
                    <span *ngIf="isLoading" class="spinner-border spinner-border-sm mr-1"></span>
                    <i class="fa fa-save" aria-hidden="true"></i> Save</button>
        </div>
      </form>
    </div>
  </div>
  <div *ngIf="licenceTemplate" class="card card-default color-palette-box">
    <form [formGroup]="licenceInfoForm" (ngSubmit)="onSubmitLicence()">
      <div class="row">
        <div class="col-12 col-md-6">
          <div class="form-group">
            <label for="licence_number">Licence Number:<span style="color:red;">*</span></label>
            <input type="text" formControlName="licence_number" placeholder="Licence Number" class="form-control" required/>
          </div>
          <div *ngIf="fl.licence_number.touched && fl.licence_number.invalid">
            <div *ngIf="fl.licence_number.hasError('required')">
              <div class="text-danger">
                Licence Number is required!
              </div>
            </div>
            <div *ngIf="fl.licence_number.hasError('minlength')">
              <div class="text-danger">
                Licence Number cannot be less than 2 characters!
              </div>
            </div>
            <div *ngIf="fl.licence_number.hasError('maxlength')">
              <div class="text-danger">
                Licence Number cannot be more than 50 characters!
              </div>
            </div>
          </div>
        </div>
        <div class="card-footer">
          <button type="submit" class="btn btn-success" [disabled]="isLoading" class="btn btn-success" (click)="licenceValidate()">
                    <span *ngIf="isLoading" class="spinner-border spinner-border-sm mr-1"></span>
                    <i class="fa fa-save" aria-hidden="true"></i> Save</button>
        </div>
      </div>
    </form>
  </div>
</div>

最初,一切正常,但突然,我收到了这个错误:

ERROR TypeError: Cannot read properties of undefined (reading 'licence_number')

来自服务。

我该如何解决这个问题?

谢谢。

ERROR TypeError: Cannot read properties of undefined (reading 'licence_number')

【问题讨论】:

    标签: angular


    【解决方案1】:
    let employee: IEmployee = {
        ...response.results.employee,
        licence_number:
                     (response.results.employee.licences &&
                      response.results.employee.licences[0] &&
                      response.results.employee.licences[0].licence_number ) 
                      ? response.results.employee.licences[0].licence_number : '';
    

    尝试更好地检查该字段是否存在,如果不存在则提供一个空字符串''

    这是一个简单的例子,说明你的支票不够。

    const c = {d: []}
    console.log(c.d);   // -> prints []
    console.log(c.d[0]); // -> prints undefined
    

    你也可以理解,总是用一些东西来修补价值是很重要的。因此,如果最终您尝试修补的值是undefined,它将失败。在这种情况下,您必须先检查是否为undefined,然后使用空字符串'' 对其进行修补。

    【讨论】:

      【解决方案2】:

      我想或者你读错了 JSON 或者输入了这种情况之一......

      if (!response) return response;
      
              if (!response.results) return response;
      
              if (!response.results.employee) return response;
      
      

      试着把这段代码改成这个

      if (!response) return response;
      
              if (!response['results']) return response;
      
              if (!response['results']['employee']) return response;
      
      

      【讨论】:

      • 您能打印出您对此代码的响应吗?
      猜你喜欢
      • 2021-12-16
      • 2018-04-29
      • 1970-01-01
      • 2021-12-03
      • 2021-11-22
      • 2019-04-15
      • 2018-11-21
      • 2020-05-25
      • 2019-03-13
      相关资源
      最近更新 更多