0

I want to show a list of IMessage on screen and be able to filter them using a Pipe. The message is actually an Observable<IMessage[]> on which I want to filter each IMessage by checking its isPrivate property. The code of the MessageStatusPipe looks like this:

export class MessageStatusPipe {
    transform(message: Observable<IMessage[]>, privateFilter: bool) {


        //Here I want to return the Messages which the pass the privateFilter, but how?

    }
}

I have read some questions which seem very similar but I don't seem to be able to apply that solution. The following solution by Luka Jacobowitz seems exactly what I need. https://stackoverflow.com/questions/37991713/simple-filter-on-array-of-rxjs-observable#=

============ Update with answer =============

As Meir pointed out the pipe returned a bool value instead of a sub array containing items that matched the filter. My working pipe now looks like this:

export class MessageStatusPipe {
    transform(messages: Observable<IMessage[]>, privateFilter: bool) {
        return messages.map(m => m.filter((message, i) => {
            return message.isPrivate == privateFilter;
        }));
    }
}
Bunnynut
  • 1,156
  • 5
  • 14
  • 37

1 Answers1

0

Your action can (should) be broken into 2 parts: 1. Getting the async values 2. Filtering them

So, you can change your pipe's signature to:

transform(messages: IMessage[], privateFilter: bool) { ... }

And in your component do:

<div *ngFor="let msg of messages | async | messageStatusPipe">...</div>

If for some reason you want to combine them into one pipe, you can have a look at an article I wrote that shows how to handle async values inside a pipe and adapt it to your needs (mainly, add your filtering loging)

============ added filter logic ==============

return messages.filter(privateFilter);
Meir
  • 14,081
  • 4
  • 39
  • 47
  • `
    ...
    ` That is actually what I already have in my component. `transform(messages: IMessage[], privateFilter: bool) { ... }` That is was my pipe used to look like but that gave an `Observable` on which I wasnt able to apply the filter.
    – Bunnynut Jul 26 '17 at 09:18
  • 1
    Your pipe should not return a bool, it should return the sub array that matches your condition – Meir Jul 26 '17 at 10:07
  • You are right, I updated my answer with a working solution. – Bunnynut Jul 27 '17 at 07:59