Reputation:
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
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