Angular 2: How to use Observable filter
Whether filter()
should be before or after map()
depends on what you want to do.
I guess in your case map()
should go before filter()
because you want to first decode data from JSON and then filter it. The way you have it now won't return anything if the condition in filter()
resolves to false
because you're using in on the entire response
. Maybe this is what you're going for...
I don't know what your response structure is but I'd go with something like this which makes more sense:
map((response: Response) => response.json().data),
filter(data => data.Type === 5),
Edit:
I'd use concatMap()
with from()
to transform the array to an Observable stream:
pipe(
map(content => response.json().data),
concatMap(arr => Observable.from(arr)),
filter(item => item.Type === 5),
).subscribe(val => console.log(val));
See live demo: http://plnkr.co/edit/nu7jL7YsExFJMGpL3YuS?p=preview
Jan 2019: Updated for RxJS 6
Here another sample based on @martin's answer:
public searchMediData(searchtearm: string) : Observable<MediData[]>
{
return this.http
.get(this.url)
.map(response => {
let data = response.json();
let medidata = data as MediData[];
return medidata;
})
.concatMap(array => Observable.from(array))
.filter(medi => {
let searchTearmUpperCase = searchtearm.toUpperCase();
let mediNameUpperCase = medi.Name.toUpperCase();
return mediNameUpperCase.includes(searchTearmUpperCase);
})
.toArray();
}