Thuta Learning
Angular
ExercisesWeb DevelopmentIntermediate

Exercise Set 2: Services, Forms & RxJS

AngularLesson 4840 min

What you'll walk away with

  • Explain the core concept and Angular data flow of Exercise Set 2: Services, Forms & RxJS
  • Run the example, predict its state and UI, and test edge and error cases
  • Apply a typed safe pattern in a real project and recognize common pitfalls

Explain it simply

Exercise Set 2: Services, Forms & RxJS, in plain language

This exercise set steps up a level from Exercise Set 1 — you'll combine services, reactive form validation, the HTTP client, and RxJS operators (map, filter) that you learned in the Intermediate/Advanced chapters. Each task reflects patterns you'll commonly see in production apps, so this practice applies directly to building real-world projects. The tasks are ordered by increasing difficulty, so you can reuse an earlier task's solution in a later one.

Problem → Why → Solution

The problem — why this concept matters

A happy-path subscription without cancellation, error, and teardown tests misses production race conditions.

A common mistake

One happy-path result does not prove the feature works; empty, loading, error, and cleanup behavior need explicit tests.

Core concept — understand how it works

This exercise set combines service and DI boundaries, form contracts, and asynchronous RxJS behavior. First document the dependency diagram, form state machine, and stream timeline, including success, error, cancellation, and cleanup behavior. Control HTTP and time with test doubles and assert user-observable results.

Mental model
  1. requirement
  2. reason and implement
  3. test and explain

Explain the core concept and Angular data flow of Exercise Set 2: Services, Forms & RxJS

Core syntax or pattern

typescript
// counter.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class CounterService {
  private countSubject = new BehaviorSubject<number>(0);
  count$ = this.countSubject.asObservable();

  increment() { this.countSubject.next(this.countSubject.value + 1); }
  decrement() { this.countSubject.next(this.countSubject.value - 1); }
  reset() { this.countSubject.next(0); }
}

// user-list.component.ts (task 3 skeleton)
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, filter } from 'rxjs/operators';

interface User { name: string; }

@Component({ selector: 'app-user-list', template: `<li *ngFor="let n of names$ | async">{{ n }}</li>` })
export class UserListComponent implements OnInit {
  names$ = this.http.get<User[]>('https://jsonplaceholder.typicode.com/users').pipe(
    map(users => users.map(u => u.name)),
    map(names => names.filter(n => n.length > 5))
  );

  constructor(private http: HttpClient) {}
  ngOnInit() {}
}

This exercise set combines service and DI boundaries, form contracts, and asynchronous RxJS behavior. First document the dependency diagram, form state machine, and stream timeline, including success, error, cancellation, and cleanup behavior. Control HTTP and time with test doubles and assert user-observable results.

Read the code step by step

  1. requirement// counter.service.ts

    This exercise set steps up a level from Exercise Set 1 — you'll combine services, reactive form validation, the HTTP client, and RxJS operators (map, filter) that you learned in the Intermediate/Advanced chapters. Each task reflects patterns you'll commonly see in production apps, so this practice applies directly to building real-world projects. The tasks are ordered by increasing difficulty, so you can reuse an earlier task's solution in a later one.

  2. reason and implementimport { Component, OnInit } from '@angular/core';

    This exercise set combines service and DI boundaries, form contracts, and asynchronous RxJS behavior. First document the dependency diagram, form state machine, and stream timeline, including success, error, cancellation, and cleanup behavior. Control HTTP and time with test doubles and assert user-observable results.

  3. test and explain}

    For each exercise, include a typed service, validated form, operator pipeline, and tests for rapid input, server failure, retry policy, and navigation cleanup.

Execution flow
  1. requirement
  2. reason and implement
  3. test and explain

Success

Explain the core concept and Angular data flow of Exercise Set 2: Services, Forms & RxJS

Failure

A happy-path subscription without cancellation, error, and teardown tests misses production race conditions.

Let's think about this for a moment

This exercise set steps up a level from Exercise Set 1 — you'll combine services, reactive form validation, the HTTP client, and RxJS operators (map, filter) that you learned in the Intermediate/Advanced chapters. Each task reflects patterns you'll commonly see in production apps, so this practice applies directly to building real-world projects. The tasks are ordered by increasing difficulty, so you can reuse an earlier task's solution in a later one.

Exercises

(1) Build a `CounterService` that holds state with a BehaviorSubject<number> and implement three methods — increment()/decrement()/reset() — then have two components share this single service and verify they stay in sync. (2) Build a SignupForm reactive form with Validators.email on the email field and Validators.minLength(6) on the password field — show error messages in the template when invalid. (3) Use HttpClient to fetch a user list from a public API (e.g., JSONPlaceholder), extract just the name fields into an array using the RxJS `map` operator, then use the `filter` operator to keep only names longer than 5 characters.

Code Example

typescript
// counter.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class CounterService {
  private countSubject = new BehaviorSubject<number>(0);
  count$ = this.countSubject.asObservable();

  increment() { this.countSubject.next(this.countSubject.value + 1); }
  decrement() { this.countSubject.next(this.countSubject.value - 1); }
  reset() { this.countSubject.next(0); }
}

// user-list.component.ts (task 3 skeleton)
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, filter } from 'rxjs/operators';

interface User { name: string; }

@Component({ selector: 'app-user-list', template: `<li *ngFor="let n of names$ | async">{{ n }}</li>` })
export class UserListComponent implements OnInit {
  names$ = this.http.get<User[]>('https://jsonplaceholder.typicode.com/users').pipe(
    map(users => users.map(u => u.name)),
    map(names => names.filter(n => n.length > 5))
  );

  constructor(private http: HttpClient) {}
  ngOnInit() {}
}
You should see
When two components share a counter service, clicking increment in one instantly updates the other component's display too; on the signup form, invalid input immediately shows an error message; and the user list only keeps names longer than 5 characters.

Real-world usage

How to apply it in a real project

For each exercise, include a typed service, validated form, operator pipeline, and tests for rapid input, server failure, retry policy, and navigation cleanup.

Mini challenge

Build it yourself

Rebuild the Exercise Set 2: Services, Forms & RxJS example without copying it. Add two normal states, one edge case, and one failure state, and write the expected UI and state transition before running it.

  • Rebuild the example without copying it
  • Test a normal input and an edge case
  • Predict the compiler or output result before running it
typescript
// counter.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class CounterService {
  private countSubject = new BehaviorSubject<number>(0);
  count$ = this.countSubject.asObservable();

  increment() { this.countSubject.next(this.countSubject.value + 1); }
  decrement() { this.countSubject.next(this.countSubject.value - 1); }
  reset() { this.countSubject.next(0); }
}

// user-list.component.ts (task 3 skeleton)
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, filter } from 'rxjs/operators';

interface User { name: string; }

@Component({ selector: 'app-user-list', template: `<li *ngFor="let n of names$ | async">{{ n }}</li>` })
export class UserListComponent implements OnInit {
  names$ = this.http.get<User[]>('https://jsonplaceholder.typicode.com/users').pipe(
    map(users => users.map(u => u.name)),
    map(names => names.filter(n => n.length > 5))
  );

  constructor(private http: HttpClient) {}
  ngOnInit() {}
}

Expected: Explain the core concept and Angular data flow of Exercise Set 2: Services, Forms & RxJS

Show hint

For each exercise, include a typed service, validated form, operator pipeline, and tests for rapid input, server failure, retry policy, and navigation cleanup.

Quick quiz 1 / 3

What best describes the core idea of Exercise Set 2: Services, Forms & RxJS?

Quick quiz 2 / 3

Which mistake should you avoid first?

Quick quiz 3 / 3

How should this be applied in a real project?

What to remember

  • requirement → reason and implement → test and explain
  • This exercise set combines service and DI boundaries, form contracts, and asynchronous RxJS behavior. First document the dependency diagram, form state machine, and stream timeline, including success, error, cancellation, and cleanup behavior. Control HTTP and time with test doubles and assert user-observable results.
  • A happy-path subscription without cancellation, error, and teardown tests misses production race conditions.
  • For each exercise, include a typed service, validated form, operator pipeline, and tests for rapid input, server failure, retry policy, and navigation cleanup.

Angular — Overview — Angular

Easy traps

  • A happy-path subscription without cancellation, error, and teardown tests misses production race conditions.
  • One happy-path result does not prove the feature works; empty, loading, error, and cleanup behavior need explicit tests.

Hands-on Exercise

Rebuild the Exercise Set 2: Services, Forms & RxJS example without copying it. Add two normal states, one edge case, and one failure state, and write the expected UI and state transition before running it.

You'll know it worked when: When two components share a counter service, clicking increment in one instantly updates the other component's display too; on the signup form, invalid input immediately shows an error message; and the user list only keeps names longer than 5 characters.

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Exercise Set 2: Services, Forms & RxJS | Thuta Learning