Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular/2 | Filter async stream

Tags:

angular

I'm passing data to a child component using the async pipe but I wish to filter the data by the value of "mimetype". However, when I add my filter I do not pick up any new objects added to the stream. For example; the following works perfectly

<asset-list [assets]="assets$ | async"></asset-list>

inside the child component I am looping through the assets to display a list. However, if I add my filter pipe for example

<asset-list [assets]="assets$ | async | imageFilter"></asset-list>

I no longer pick up any changes to the stream. My pipe reads as follows:

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

@Pipe({
    name: 'imageFilter'
})
@Injectable()
export class AssetImagesPipe implements PipeTransform {

    transform(assets: any[] ) {

        var images = [];

        for( let i in assets ) {

            if( assets[i].mimetype.substring(0,5) == 'image' )
            {
                images.push( assets[i] );
            }
        }

        return images;
    }
}

Any advice is greatly appreciated.

like image 554
prime Avatar asked Nov 20 '25 08:11

prime


1 Answers

There are two possible ways:

Set your Pipe to pure: false (https://angular.io/guide/pipes#pure-and-impure-pipes)

or use it before that async-pipe..

Impure-pipe:

@Pipe({
    name: 'imageFilter',
    pure: false
})
export class AssetImagesPipe implements PipeTransform {

    transform(assets: any[] ) {
      if (!assets || !assets.length) return [];
      return assets.filter(...);
    }
}

Before async-pipe:

@Pipe({
    name: 'imageFilter$'
})
export class AssetImagesAsyncPipe implements PipeTransform {

    transform(assets$: Observable<any[]>) {
      if (!assets$) return undefined;
      return assets$.map(assets => assets.filter(...));
    }
}

See my plunker: https://plnkr.co/edit/Q2Yw2TjdpGqA4dWBxfZ0?p=preview

like image 182
slaesh Avatar answered Nov 22 '25 20:11

slaesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!