Member-only story
RxJs: Transforming Data - Understanding the Power of Operators
RxJS provides a powerful way to transform data streams using operators like map
, filter
, and mergeMap
. One of the most commonly used operators is map
, which allows us to modify emitted values before they reach the observer.
Implementing
normalizeUsers
Function in RxJS
Problem Statement
We receive an observable (users$
) that emits an array of UserInterface objects. Our goal is to transform this data stream and return an observable that emits only the users' names.
User Interface Definition
interface UserInterface {
id: string;
name: string;
age: number;
}
Solution Using RxJS map
Operator
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
// Sample user data
const users$: Observable<UserInterface[]> = of([
{ id: '1', name: 'Alice', age: 25 },
{ id: '2', name: 'Bob', age: 30 },
{ id: '3', name: 'Charlie', age: 22 }
]);
// Function to normalize users and return an observable of names
function normalizeUsers(users$: Observable<UserInterface[]>): Observable<string[]> {
return users$.pipe(
map(users => users.map(user => user.name)) // Extracts only names
);
}
// Subscribe and log output
normalizeUsers(users$).subscribe(names => console.log(names));
Expected Output
["Alice", "Bob", "Charlie"]