1

I'm new to Angular2/Typescript and have been stuck on this for almost a day. I'm sure this must be something simple that I'm missing:

This is my view: noticias.html

<ion-list id="NewsList" no-margin>
    <ion-item no-padding *ngFor="let item of newsData | newsfilter">
    ...
    </ion-item>
</ion-list>

I need to filter that list in this newsfilter pipe.

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

@Pipe({
    name: 'newsfilter'
})

export class NewsfilterPipe implements PipeTransform {

    transform(array: any[]) {        
        console.log(array.length);        
    }

}

Right now, when I console.log the array, I get an array with a couple of objects in it, which is what I would expect.

console.log(array)

However, and this is what's confusing me, when I console.log(array.length) I get "undefined is not an object (evaluating 'array.length'). I also can't access any keys in these objects like array[0].id, for example.

Can someone please help in explaining what I'm doing wrong here? Thanks in advance.

3 Answers 3

1

Are you sure the newsData field cannot be undefined or null?

Your filter should be able to handle this possibility.

transform(array: any[]) {

    if (!array) return;      
    console.log(array.length);        
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this as a signature on your transform method

transform(value: any, args? any): any {
  console.log(value.length);
}

Comments

0

a colleague of mine had the same problem lately. How and when do you set the value of newsData and what's the initial value here?

The thing is, that a pipe is executed immediately when the view renders (afaik). Meaning, that the value of newsData probably could be undefined when the pipe is executing the first time and that's ok. If I remember correctly, it executes even before ngOnInit lifecycle hook is called.

Adding an if to the pipe checking for an existing value should be the solution. After you assign the real value to newsData, the pipe is executed automatically again and the value should be correct.

EDIT: To check this, console.log('## array:', array); should be shown two times in the console. First with ## array: undefined and second with the correct value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.