I have a problem, I get the error "core.js:4196 ERROR TypeError: Cannot read properties of undefined (reading 'phones')"
The thing is that it tells me that the array of objects that I am going through is empty, when checking a little and doing debugging, I realize that it is not. That actually does not come indefinitely, the data is something big, yes, among 2800 data it brings you almost 5 or 6 phones (since those are what are registered)
Anyway, what I really want to do is get the phone numbers of "x" users from an object and do an autocomplete filtering the data.
I leave you the code, maybe you see something that I don't:
.TS
contactos: AddContacto[] = [];
filteredContacts: Observable<AddContacto[]>;
phoneControl: FormControl = new FormControl();
this.filteredContactos = this.phoneControl.valueChanges.pipe(
startWith(null),
map((search: string | null) => (search ? this._filterContactos(search) : this.contactos.slice())),
);
private _filterContactos(search: string) {
const filterValue = search.toLowerCase();
return this.contact.filter(
(contact) =>
!!contact.phones.find((email) => contact.includes(search)) ||
contact.fullName.toLowerCase().includes(filterValue),
);
}
.HTML
<div >
<mat-form-field fxFlex="100" appearance="outline" fxFlex="100">
<mat-label>Search Client</mat-label>
<input type="text" placeholder="Add email..." matInput [formControl]="phoneControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" >
<mat-option *ngFor="contact of filteredContacts | async" [value]="contact.phones[0]">
{{contact?.phones[0]}} {{contact?.fullName ? '(' contacto?.nombre_completo ')' : ''}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<small-loading [loading]="loading"></small-loading>
</div>
Object
0: {
"state": true,
"coments": null,
"phones": ["22222222"],
"emails": [
"[email protected]"
],
"fullName": "",
"_id": "",
"bitacora": {},
"__v": 0
}
Thanks!!
CodePudding user response:
That error is because you are using an old version of typescript and it is necessary to check if the array exist and length is higher that 0 to use any array method like filter, find, foreach, etc.
Change this in your _filterContactos method.
private _filterContactos(search: string) {
const filterValue = search.toLowerCase();
return this.contact.filter(
(contact) => {
if (contact.phones && contact.phones.length > 0) {
!!contact.phones.find((email) => contact.includes(search)) ||
contact.fullName.toLowerCase().includes(filterValue)
}
}
);
}
Let me know if it worked for you.
CodePudding user response:
You trying to read data of object that doesn't exist.
err.response.data Try to console.log(err) and console.log(err.response) You will probably see that you have something wrong in your response.