Custom pipe returns no results

Hi there,

I have an array of orders, that look like that:

[
    { "orderNumber": 1, "products": [ { "id": 0}, { "id": 5} ] },
    { "orderNumber": 2, "products": [ { "id": 5}, { "id": 6} ] }
 ]

And then I’m trying to show only those orders, that contain the particular product id:

<div *ngFor="let order of orders | orderContainsSelectedProduct:product.id">
    <p>{{ order.orderNumber}}</p>
</di>

orderContainsSelectedProduct:product pipe looks like that:

export class OrderContainsSelectedProductPipe implements PipeTransform {
  	transform(values: any, id: number): any {
        if(values) {
            return values.filter(value => value.products.id === id);
        }else{
            console.log('no orders containing selected product');
        }
    }
}

And it returns nothing at all, so no orders are showing even if I replace the “orderContainsSelectedProduct:product.id” with “orderContainsSelectedProduct:5”

Please, let me know what I’m doingwrong here.

Regards,
Olga

products is an array and not an object, and so won’t have id on itself.

So you’d want to do something like:

return values.filter(value => value.products.findIndex(product => product.id === id) > -1);

On a more general note though, I’d recommend moving this into your controller as doing something like this via a pipe can be rather un-performant.

I’d also suggest adding types, as it can help catch errors like this ;).

1 Like

Hmm, I though that separating pipes from the component is actually a logical thing to do… Is it not? When is it the best to put it in the pipe and when it’s not?

Thanks a lot!