How to Use map Operator in RxJS for Angular
In RxJS, use the
map operator to transform the values emitted by an observable by applying a function to each value. You apply map inside the pipe() method of an observable to create a new observable with transformed data.Syntax
The map operator takes a function that defines how to transform each emitted value from the source observable. It is used inside the pipe() method.
sourceObservable.pipe(map(value => transformedValue))valueis each item emitted by the source observable.- The function returns the transformed value.
typescript
import { of } from 'rxjs'; import { map } from 'rxjs/operators'; const source$ = of(1, 2, 3); const mapped$ = source$.pipe( map(value => value * 2) ); mapped$.subscribe(console.log);
Output
2
4
6
Example
This example shows how to double numbers emitted by an observable using map. The source observable emits 1, 2, and 3. The map operator multiplies each number by 2, so the output is 2, 4, and 6.
typescript
import { of } from 'rxjs'; import { map } from 'rxjs/operators'; const numbers$ = of(1, 2, 3); const doubledNumbers$ = numbers$.pipe( map(num => num * 2) ); doubledNumbers$.subscribe(value => console.log(value));
Output
2
4
6
Common Pitfalls
Common mistakes when using map in RxJS include:
- Not using
pipe()to applymap. The operator must be insidepipe(). - Forgetting to subscribe to the observable, so no output appears.
- Using
mapwhen you want to perform side effects; usetapinstead.
typescript
import { of } from 'rxjs'; import { map } from 'rxjs/operators'; // Wrong: map used outside pipe const source$ = of(1, 2, 3); // const wrongMapped$ = map(value => value * 2)(source$); // This works but is less readable // Right: map inside pipe const correctMapped$ = source$.pipe( map(value => value * 2) ); correctMapped$.subscribe(console.log);
Output
2
4
6
Quick Reference
| Concept | Description |
|---|---|
| map | Transforms each emitted value by applying a function |
| pipe() | Chains multiple RxJS operators |
| subscribe() | Starts the observable execution and handles output |
| tap | Performs side effects without changing values |
| of | Creates an observable from values |
Key Takeaways
Use the map operator inside pipe() to transform observable values.
Always subscribe to the observable to see the output.
Use map for data transformation, not side effects.
pipe() allows chaining multiple operators cleanly.
Remember to import map from 'rxjs/operators'.