BACK
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

  1. Inside pipe(...), add map(user => 'User #' + user.id + ': ' + user.name).
  2. Each user object turns into a finished string.
  3. Expected output:
    User #1: Ada
    User #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 // TypeScript
CONSOLE · Console output
Hit Run to see the result...