How to Use filter Operator in RxJS with Angular
Use the
filter operator in RxJS to let only values that meet a condition pass through an observable stream. Import filter from rxjs/operators and apply it inside the pipe() method to filter emitted values based on a function.Syntax
The filter operator takes a predicate function that returns true or false. It emits only those values from the source observable for which the predicate returns true.
- predicate: A function that receives each value and returns a boolean.
- pipe(): Used to chain operators like
filter.
typescript
import { filter } from 'rxjs/operators'; sourceObservable.pipe( filter(value => /* condition returning true or false */) );
Example
This example shows how to filter numbers emitted by an observable to only allow even numbers to pass through.
typescript
import { of } from 'rxjs'; import { filter } from 'rxjs/operators'; const numbers$ = of(1, 2, 3, 4, 5, 6); numbers$ .pipe( filter(num => num % 2 === 0) ) .subscribe(value => console.log(value));
Output
2
4
6
Common Pitfalls
One common mistake is forgetting to import filter from rxjs/operators, which causes errors. Another is placing filter outside the pipe() method, which will not work. Also, ensure the predicate function returns a boolean; otherwise, filtering won't behave as expected.
typescript
/* Wrong way: filter used outside pipe */ import { of } from 'rxjs'; import { filter } from 'rxjs/operators'; const source$ = of(1, 2, 3); // This will cause an error // source$.filter(x => x > 1).subscribe(console.log); /* Right way: filter inside pipe */ source$ .pipe( filter(x => x > 1) ) .subscribe(console.log);
Output
2
3
Quick Reference
Remember these tips when using filter in RxJS:
- Always import
filterfromrxjs/operators. - Use
filterinside thepipe()method. - The predicate function must return a boolean.
filterdoes not modify values, only decides which to emit.
Key Takeaways
Use the filter operator inside pipe() to emit only values that meet a condition.
Import filter from rxjs/operators to avoid errors.
The predicate function must return true or false for filtering to work.
filter does not change values, it only controls which values pass through.
Always place filter inside the pipe method, never outside.