AI Hints
Home›Angular Tutorial›Providers, Injection Tokens and Practice: A Wishlist Service
Angular · Lesson 72 of 120

Practice: A Wishlist Service

Your turn.

⏱ 2 min read▶ Video at 1:25:42🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Let's practise services. You'll write a wishlist service, that keeps the books a user likes.

  • A wishlist
  • A service
  • Your turn

A wishlist service

Your turn. Pause the video, and try this. Write a wishlist service, with a private signal of titles, a read-only copy, and a computed count. Toggle adds a title, or removes it if it's already there. Here is one solution. The list is private. Has checks for a title. And toggle either filters it out, or adds it. We liked Dune, Emma, and Circe, then unliked Dune. So two are left.

✍️ Exercise: A wishlist service

Wishlist service: private signal of titles, read-only "titles", computed "count", has(t), toggle(t). Show ♥/♡ per book and "Wishlist: N".

Show hint

toggle: this.list.update(l => l.includes(t) ? l.filter(x => x !== t) : [...l, t])

Show solution
wishlist.tstypescript
import { Service, signal, computed } from '@angular/core';

@Service()
export class Wishlist {
  private readonly list = signal<string[]>([]);
  readonly titles = this.list.asReadonly();
  readonly count = computed(() => this.list().length);

  has(title: string) {
    return this.list().includes(title);
  }

  toggle(title: string) {
    this.list.update(l => (l.includes(title) ? l.filter(t => t !== title) : [...l, title]));
  }
}

app.ts

The component injects the wishlist. Each button toggles its book, and shows a full heart, when the book is in the list. The heading reads the computed count.

app.tstypescript
import { Component, inject } from '@angular/core';
import { Wishlist } from './wishlist';
import { BOOKS } from './books';

@Component({
  selector: 'app-root',
  template: `
    <h2>Wishlist: {{ wish.count() }}</h2>
    @for (b of books; track b.id) {
      <p>{{ b.title }}
        <button (click)="wish.toggle(b.title)">
          {{ wish.has(b.title) ? '♥' : '♡' }}</button></p>
    }
  `,
})
export class App {
  wish = inject(Wishlist);
  books = BOOKS;
}

What module eight taught

Services hold shared data, and logic. The service decorator provides them automatically, and inject gets them. Private signals, with as read only, protect the state. Providers, and tokens, control what gets created, and where.

keyvalue
@Service()a shared class
inject()ask for it
private + asReadonly()protect the state
providers, tokenswhat and where

Summary

Your components can now share data through services. That's the end of module eight. Next, routing, and pages.

Key takeaways
  • Services
  • inject()
  • Providers
Next up: What Routing Is — pages in one app