user9871690
user9871690

Reputation:

How do I solve ERROR TypeError: Cannot read property 'forEach' of undefined in Angular?

I'm trying to display movie categories and I get an Error: cannot read property of 'forEach' of undefined but my code runs as expected. I don't know why this errors pops up while I inspect in google chrome.

Category-list.pipe.ts

import { Pipe } from '@angular/core';

@Pipe({
    name: 'categoryList'
  })
  export class CategoryListPipe {
    transform(mediaItems) {
      var categories = [];
      mediaItems.forEach(mediaItem => {
        if (categories.indexOf(mediaItem.category) <= -1) {
          categories.push(mediaItem.category);
        }
      });
      return categories.join(', ');
    }
  }

media-item-list.component.html

<nav>
    <a (click)="getMediaItems('')">
      All
    </a>
    <a (click)="getMediaItems('Movies')">
      Movies
    </a>
    <a (click)="getMediaItems('Series')">
      Series
    </a>
  </nav>

  <header 
  [ngClass]="{'medium-movies':medium === 'Movies', 'medium-series':medium === 'Series'}">
   {{ medium }}
   {{ mediaItems | categoryList }} 
</header>

<section>
  <app-media-item
  [ngClass]="{'medium-movies': mediaItem.medium==='Movies', 'medium-series':mediaItem.medium==='Series'}" 
  *ngFor="let mediaItem of mediaItems"
  [mediaItem]="mediaItem"
  (delete)="onMediaItemDelete($event)"></app-media-item>
</section>

Upvotes: 0

Views: 523

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39432

The transform method of your pipe runs even before mediaItems are populated. That's why you're getting that error. But after that, since mediaItems get populated again and the transform method runs again, it's all working as expected.

To not get the error in the first place, in your pipe's transform method, check if mediaItems is defined. If it is defined, then only perform the operation. Send then mediaItems as is otherwise(as it's value is null).

Upvotes: 1

Related Questions