首页 > 解决方案 > Angular - 'IContact[] 类型的参数 | 未定义的'不可分配给'IContact []'类型的参数

问题描述

在 Angular-12 项目中,我有这个 JSON API 响应:

    {
      "message": "Employee Detail.",
      "error": false,
      "code": 200,
      "results": {
        "employee": {
            "id": 8,
            "first_name": "JONAH",
            "last_name": "YAKUBU",
            "other_name": "AKWETEY",
            "employeecontacts": [
                {
                    "id": 1,
                    "phone_type_id": 2,
                    "employee_id": 8,
                    "phone_number": "014566778",
                    "is_primary_contact_number": 1,
                    "phonetypes": {
                        "id": 2,
                        "type_name": "Arena",
                    }
                },
                {
                    "id": 2,
                    "phone_type_id": 3,
                    "employee_id": 8,
                    "phone_number": "016766709",
                    "is_primary_contact_number": 0,
                    "phonetypes": {
                        "id": 2,
                        "type_name": "Office",
                    }
                }
            ]
          }
      }
    }

界面:

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

    export interface IEmployee {
      id?: number;
      first_name?: string;
      other_name?: string;
      last_name?: string;
      employeecontacts?: IContact[];
    }

    export interface IContact {
      id?: number;
      phone_number: string;
      phone_type_id?: number;
      phonetypes?: {id:number,type_name:string};
      is_primary_contact_number?: boolean;
    }

服务:

    getEmployeeById(id: number): Observable<EmployeeResponse> {
      return this.http.get<EmployeeResponse>(this.api.baseURL + 'employees/fetchbyid/' + id, this.httpOptions);
    }

    public updateEmployee(id: number, employee: IEmployee): Observable<any> {
      return this.http.put(this.api.baseURL + 'employees/update/' + id, employee, this.httpOptions);
    }

零件:

_id!: number;
contactInfoForm!: FormGroup;
contactdata!: IEmployee;

ngOnInit(): void {
  this.isLoading = true;
  this._id = this.route.snapshot.params['id'];
  this.updateContact();
  this.loadContactById();
}

loadContactById() {
  this.employeeService
    .getEmployeeById(this._id)
    .subscribe((data: EmployeeResponse) => {
      this.contactdata = data.results.employee;
      this.contactInfoForm.patchValue({
        first_name: this.contactdata.first_name,

      });
    });
  this.contactInfoForm.setControl('contacts', this.SetExistingContacts(this.contactdata.employeecontacts));
}

SetExistingContacts(contactSets: IContact[]): FormArray {
  const formarray = new FormArray([]);
  contactSets.forEach(c => {
    formarray.push(this.fb.group({
      phone_number: c.phone_number,
      phone_type_id: c.phone_type_id,
      is_primary_contact_number: c.is_primary_contact_number
    }));
  });
  return formarray;
}

updateContact() {
  this.contactInfoForm = this.fb.group({
    id: [''],
    first_name: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(50)]],
    contacts: this.fb.array([
      this.addContactFormGroup()
    ])
  });
}

addContactFormGroup(): FormGroup {
  return this.fb.group({
    phone_type_id: ['', Validators.required],
    phone_number: ['', [Validators.required, Validators.maxLength(15)]],
    is_primary_contact_number: ['']
  });
}

public addContactButtonClick() {
  const contacts = this.contactInfoForm.get('contacts') as FormArray
  contacts.push(this.addContactFormGroup())
}

get contacts() {
  return this.contactInfoForm.controls['contacts'] as FormArray;
}

getContactFormGroup(index: number): FormGroup {
  return this.contacts.at(index) as FormGroup;
}

我想将数据加载到动态 FormArray 中,然后对其进行更新。

我从组件中得到了这个错误:

Argument of type 'IContact[] | undefined' is not assignable to parameter of type 'IContact[]'.

类型“未定义”不可分配给类型“IContact[]”.ts(2345)

此行突出显示:

(this.contactdata.employeecontacts));

在:

this.contactInfoForm.setControl('联系人', this.SetExistingContacts(this.contactdata.employeecontacts));

如何解决错误然后更新数据?

谢谢

标签: angular

解决方案


您的IEmployee界面有一个可选属性:

employeecontacts?: IContact[];

因此,预计会有该错误消息。Typescript 不知道它是否会是undefined一个实际值。

尝试以下操作:

 this.contactInfoForm.setControl(
      'contacts', 
      this.SetExistingContacts(this.contactdata.employeecontacts!) //note the ! at the end
 );

另外,我注意到错误所在的代码行,它应该在subscribe函数内部。您正在将数据存储到this.contactdata其中并且您试图走出去employeecontacts,它还没有任何数据。

loadContactById() {
  this.employeeService
    .getEmployeeById(this._id)
    .subscribe((data: EmployeeResponse) => {
      this.contactdata = data.results.employee;
      this.contactInfoForm.patchValue({
        first_name: this.contactdata.first_name,
      });
     
     this.contactInfoForm.setControl(
        'contacts', 
        this.SetExistingContacts(this.contactdata.employeecontacts)
     );
    });
 }

推荐阅读