Home > Software engineering >  Cannot read properties of undefined (reading 'filter')
Cannot read properties of undefined (reading 'filter')

Time:08-25

I'm trying to get into Angular after a few months without programming and have decided to code a cascading dropdown menu. I was trying to do the second part of the cascade and my code was looking like this:

onSelect(event_type:any){
    this.dropdownListService.getAll().subscribe((res:any)=>{
      this.properties = res['properties'].filter((res:any) => res.event_type == event_type!.value),
      console.log(this.properties);
    })
  }

The only problem is that I'm getting

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

I can't understand, why is it undefined?

CodePudding user response:

There might be 2 problems happened in your case. One is the res['properties'] is not a json array and another one is res['properties'] must be undefined. You can handle it like below,

onSelect(event_type:any){
    this.dropdownListService.getAll().subscribe((res:any)=>{
     if(res['properties'] != undefined && res['properties'].length > 0){
      this.properties = res['properties'].filter((res:any) => res.event_type == event_type!.value),
      console.log(this.properties);
     }
    })
  }

CodePudding user response:

I can't understand, why is it undefined?

The simple reason is that the service response is undefined. That is what the error says:

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

This means res['properties'] is not an Array but undefined.

You can add one filter() operator:

this.dropdownListService.getAll()
.pipe(
   filter(resp => resp !== undefined && resp !== null)
).subscribe((res:any)=>{

Or as the other answer says like have a condition to check in the subscription block.

Use the condition as you like but better to debug why it is failing to give response.

  • Related