10 RxJS operators which I use daily as an Angular developer
As an Angular developer, you might find the following RxJS operators useful in your daily development:
map()
: This operator is used to transform values emitted by an observable. It takes a function as an argument, which receives the emitted value as an input and returns a transformed output. The returned output is emitted as the new value of the observable. For example, you can use map()
to convert a stream of user objects into a stream of user names:
import { map } from 'rxjs/operators';
import { UserService } from './user.service';
constructor(private userService: UserService) {}
this.userService.getUsers().pipe(
map(users => users.map(user => user.name))
).subscribe(names => console.log(names));
filter()
: This operator is used to filter out values emitted by an observable based on a condition. It takes a function as an argument, which receives the emitted value as an input and returns a boolean. If the boolean is true, the value is emitted, otherwise, it is filtered out. For example, you can use filter()
to only keep even numbers from a stream of integers:
import { filter } from 'rxjs/operators';
import { of } from 'rxjs';
of(1, 2, 3, 4, 5, 6).pipe(
filter(num => num % 2 === 0)
).subscribe(evenNum => console.log(evenNum));