Leonardo Rodrigues
Leonardo Rodrigues

Reputation: 53

Cannot read properties of undefined (reading 'filter')

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?

Upvotes: 1

Views: 4175

Answers (3)

codewithharshad
codewithharshad

Reputation: 361

Just add question mark after like res['properties']?.filter.

 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);
        })
      }

Upvotes: 1

Jai
Jai

Reputation: 74738

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.

Upvotes: 1

Sujith Sandeep
Sujith Sandeep

Reputation: 1249

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);
     }
    })
  }

Upvotes: 0

Related Questions