AJ-
AJ-

Reputation: 1783

Angular 6 - cannot read property of null, using a filter method

pretty new to angular so this might be an easy question!

I have an observable that returns me a list of objects.

These objects have an optional property, and I'm trying to filter the list of objects based on that property.

getPersonWithHouse(houseID: string): Person[] {
  this.myService.getPersons().subscribe(persons => {
     this.personsWithHouse = persons.filter(person => {
         if (person.house) return person.house.id === houseID;
     });
   });
 return this.personsWithHouse;
}

so basically in this function I take a House as argument, then I subscribe to the list of all the persons, and I save in a variable all the persons that are in that house.

I keep getting "cannot read property "ID" of null"

and also a "not all code paths return a value", but this is because I put an If without an else, but I don't know what else I could put there.

How can I fix this? the main issue is that if every person has a house, this would work, but as the house property is optional, some persons don't have one, so I get this error

thank you

Upvotes: 0

Views: 563

Answers (2)

M3ghana
M3ghana

Reputation: 1281

Try this -

persons.filter((person) => person.house && person.house.id && (person.house.id === houseID));

Upvotes: 0

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41447

Add another condition

if (person.house && person.house.id) return person.house.id === houseID;
return false;

Upvotes: 1

Related Questions