Lessons14. map: DTO to ViewModel
Lessons · 14
14. map: DTO to ViewModel
A real case: DTO → ViewModel
In Angular apps, server data usually arrives in one shape (called a DTO — Data Transfer Object), while the component prefers another (often called a ViewModel). map is the standard tool for that conversion.
The pure-transformation rule
map should be a pure function: take a value → return a new value. No console.log, no mutating outside variables, no firing analytics, and so on. When you need side effects, there's a dedicated operator for them — tap — which we'll cover later.
Glossary
- DTO — the data structure the server hands you.
- ViewModel — a structure convenient for display in the UI (ready-made strings, flags, classes).
- Pure function — a function with no side effects: the same input always gives the same output, and it changes nothing around it.
Your task
- Inside
pipe(...), addmap(user => 'User #' + user.id + ': ' + user.name). - Each user object turns into a finished string.
- Expected output:
User #1: AdaUser #2: Linus
Solution spoiler · click to reveal
const { from, map } = Rx;
const users = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Linus' }
];
const labels$ = from(users).pipe(
map(user => 'User #' + user.id + ': ' + user.name)
);
labels$.subscribe(label => console.log(label)); script.ts
CONSOLE · Console output
Hit Run to see the result...