3

I currently have an array of observables which I'm iterating over using an *ngFor loop with the async pipe. I would like to filter the observables by a property value on the object, e.g

Original array:

[{ name: test1,
   type: type1},
 { name: test2,
   type: type2}
 { name: test3,
   type: type1}
 { name: test4,
   type: type2}]

I would like to filter this and make two new observable (arrays), one for type1 and one for type2

I tried obs.filter(x => x.type == "type1) but it returns nothing

I then tried obs.mergeAll().filter(x => x.type == "type1") and I can subscribe to this and log it to the console correctly but now it doesn't work with my *ngFor (async pipe). I'm guessing it's because the mergeAll means it's no longer an observable array? So do I need to convert it back?

3
  • What type is obj.type? string? Commented Dec 12, 2016 at 10:05
  • Yes it's a string Commented Dec 14, 2016 at 9:19
  • @AnjilDhamala Please don't edit posts to add random italic and bold markdown. The code markdown was ok (if incomplete), but the rest only made it harder to read. Commented Apr 5, 2019 at 19:31

1 Answer 1

1

You are probably missing pipe operator from RXJS6.

import { of, from } from "rxjs";

import { filter, map } from "rxjs/operators";

const obs = from([{
    name: 'test1',
    type: 'type1'
},
{
    name: 'test2',
    type: 'type2'
},
{
    name: 'test3',
    type: 'type1'
},
{
    name: 'test4',
    type: 'type2'
}]);

const source = obs.pipe(
    filter(data => data.type === 'type2')
)


console.log(source.subscribe(item => console.log(item)));
// prints {name: "test2", type: "type2"}
{name: "test4", type: "type2"}

If you want to get an array:


const items = [];
console.log(source.subscribe(item => items.push(item)));
console.log(items);

Sign up to request clarification or add additional context in comments.

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.