Featured resource
2026 Tech Forecast
2026 Tech Forecast

1,500+ tech insiders, business leaders, and Pluralsight Authors share their predictions on what’s shifting fastest and how to stay ahead.

Download the forecast
  • Lab
    • Libraries: If you want this lab, consider one of these libraries.
    • Core Tech
Labs

Building Services with Dependency Injection in Angular

In this Code Lab, you'll use Angular services and dependency injection to move data access and shared state out of components and into reusable, injectable classes. You'll fetch typed data through a service, keep several views in sync with signal-based state, and configure a service with an injection token. By the end of this lab, you'll see how the place where you provide a service decides whether the whole app shares one instance or a single section gets its own.

Lab platform
Lab Info
Level
Intermediate
Last updated
Dec 05, 2026
Duration
40m

Contact sales

By clicking submit, you agree to our Privacy Policy and Terms of Use, and consent to receive marketing emails from Pluralsight.
Table of Contents
  1. Challenge

    Introduction

    Welcome to the lab!


    Joe's Robot Shop has a problem that many growing Angular apps run into: every page builds or stores its own data, so nothing stays consistent from one view to the next. You'll fix that by moving data access and shared state out of the pages and into services that Angular creates and hands to each component that asks for them.

    In this lab, you'll turn the shop's hard-coded catalog into one served by a typed API service, give every page one shared signal-based cart, and then give the Bot Squad section a separate cart without changing the cart code.

    • Fictional names only. No affiliation with or endorsement by any real company.

    The lab's codebase lives in the application directory, which already contains the Joe's Robot Shop project with its pages, product data, and local API server, and every file path in this lab is relative to it. info> Feeling stuck? Check out the solution/stepN/ folder that matches one less than the first number of the task you're on, such as solution/step1/ for Tasks in Step 2, to see a working implementation. Give it a try on your own first.

  2. Challenge

    Create and inject the products service

    Right now, the Catalog and Search pages each import the shop's hard-coded product array directly. Here, you'll create a root-provided products service that owns that data, and then inject it into both components with inject(). By the end of this step, the Catalog and Search pages get their products from that service instead of importing the product array directly. ### Root-provided services

    A service is a class that holds logic or data that more than one component needs. When you mark a class with @Injectable({ providedIn: 'root' }), Angular's root injector creates a single instance of it the first time something asks for it, and every component that asks afterward receives that same instance. You don't list the service in any providers array, and if nothing ever uses it, the build can drop it. Prefer providedIn: 'root' for app-wide services over registering them by hand.

    @Injectable({ providedIn: 'root' })
    export class WidgetService {
      getWidgets(): Widget[] {
        return widgetList;
      }
    }
    

    In this lab, src/app/catalog/products.service.ts already imports Injectable, the Product type, and the shop's existing productsArray data, so the service only needs its class. ### Injecting a service with inject()

    To use a service, a component asks Angular for it with the inject() function from @angular/core. Call inject() in a field initializer, which Angular runs while it creates the component. Prefer this over listing the service as a constructor parameter: it keeps the dependency next to the field that uses it, and it's the form the current Angular docs use.

    export class WidgetListComponent {
      private widgetService = inject(WidgetService);
      protected widgets = this.widgetService.getWidgets();
    }
    
  3. Challenge

    Retrieve product data with HttpClient

    With ProductsService in place, every product page now depends on one class, so changing where products come from takes a single edit. Here, you'll replace the hard-coded array with a typed HttpClient request to the shop's API. The request returns an observable, so the products arrive some time after each page first loads, and each page needs a way to show them once they do.


    You'll handle that in two ways. The Catalog page will use the async pipe, which subscribes to the observable from the template and displays each value it emits. The Search page will subscribe in its component code and store the products in a signal. A signal is a container for a value that Angular tracks: you create one with signal(), read its current value by calling it, as in products(), and replace that value with set(). When a signal that a template reads changes, Angular updates the page, which makes a signal the dependable place to keep data that arrives after the page first renders. By the end of this step, both pages display products loaded from /api/products, and in the next step you'll use signals again to share one cart across the app. ### Typed HTTP requests from a service

    HttpClient is Angular's service for making HTTP requests. It's provided in the root injector by default, so you obtain it with inject(HttpClient) from @angular/common/http without adding provideHttpClient() to app.config.ts. Its get() method takes a type argument that describes the response body and returns an Observable of that type. The request is sent only when something subscribes.

    getWidgets(): Observable<Widget[]> {
      return this.http.get<Widget[]>('/api/widgets');
    }
    

    Once getProducts() returns an observable, the editor flags errors in CatalogComponent and SearchComponent, because both still expect an array. That's expected at this point, and you'll fix both components in the next task. ### Two ways to consume an observable

    To use the async pipe, add AsyncPipe from @angular/common to the component's imports array and apply the pipe where the template reads the observable, as in @for (widget of widgets | async; track widget.id). The pipe also unsubscribes when the component is destroyed. For the signal approach, start the signal with an empty array so the page can render before the data arrives, and call set() from the subscription.

    protected widgets = signal<Widget[]>([]);
    
    ngOnInit() {
      this.widgetService.getWidgets().subscribe((list) => this.widgets.set(list));
    }
    
  4. Challenge

    Share cart state with signals

    Your pages now share one source of product data, but each one still keeps its own private cart array. That's why items bought on the Catalog page never show up on the Cart page. So far, a signal has held data for a single page. Here, you'll move the cart's state into a root-provided CartService and keep it in a signal there, so every page that buys or hires updates the same signal and the Cart page reads from it.


    Because many components now depend on that one signal, you're going to want to protect it. The writable signal stays private to the service, and components receive a read-only view of it through asReadonly(). Changes go through service methods that call update(), which derives each new cart from the previous one instead of replacing it outright. You'll also derive the cart total with computed(), which creates a signal whose value is calculated from other signals and recalculates whenever they change. By the end of this step, every page should show the same cart and total. ### Private signals and read-only views

    A signal's asReadonly() method returns a view of the same signal that components can read but that has no set() or update() method. Declare the writable signal with private, and expose only the read-only view as a public member.

    export class SessionService {
      private currentUser = signal<User | null>(null);
      readonly user = this.currentUser.asReadonly();
    }
    ``` ### Updating a signal from its previous value
    
    A signal's `update()` method takes a function that receives the current value and returns the next one. Return a new array instead of changing the existing one, because Angular detects a change only when the signal holds a different value. Spreading into a new array adds an item, and `filter()` removes one.
    
    ```ts
    this.tags.update((list) => [...list, newTag]);
    ``` ### Derived state with `computed()`
    
    Angular caches the value of a `computed()` signal and recalculates it only when a signal it reads changes. Declare it as a field so every reader shares one signal, instead of a getter that creates a new calculation on each read.
    
    ```ts
    readonly itemCount = computed(() => this.items().length);
    

    Each product's price after its discount is price * (1 - discount). ### Sharing one service across components

    Because CartService is provided in root, every component that injects it receives the same instance, so a product added on one page is in the cart on every other page. Each buying page only needs to forward its clicks to the service and drop the array it keeps on its own. ### Reading service signals in a template

    A component can expose a service's signals as its own fields and read them in its template by calling them, as in @if (items().length === 0). Because the template reads signals, Angular updates the page whenever the cart changes, with no getters or manual refresh.

  5. Challenge

    Configure the cart with an injection token

    Every page now shares one reactive cart, but CartService has no way to receive settings, such as whether to save the cart and under which localStorage key. Here, you'll define an injection token for those settings, register the shop's values for it in app.config.ts, and then inject the token into CartService to load and save the cart. By the end of this step, the shop's cart survives a page refresh. ### Injection tokens

    Angular looks up a class dependency by the class itself, but the cart settings are a plain CartOptions object, a type defined in src/app/catalog/cart-storage.ts, which has no class to look up. An InjectionToken is a unique key that stands in for a non-class dependency. Its type argument tells TypeScript what inject() returns for it, and the string you pass is a description that appears in error messages.

    export const THEME_TOKEN = new InjectionToken<ThemeSettings>('THEME');
    ``` ### `useValue` providers
    
    A provider tells an injector what to return for a token. A `useValue` provider returns the object you give it, which suits fixed settings. Providers in `app.config.ts` belong to the root injector, so the whole app can inject them.
    
    ```ts
    { provide: THEME_TOKEN, useValue: { mode: 'dark' } }
    ``` ### Injecting a token into a service
    
    You inject a token the same way you inject a class: `inject(THEME_TOKEN)` returns the provided value. `src/app/catalog/cart-storage.ts` already provides `loadCart(options)`, which returns the saved cart for those options, and `saveCart(options, cart)`, which writes it. Field initializers run from top to bottom, so a field that reads the options must be declared after the field that injects them.
  6. Challenge

    Isolate the Bot Squad cart with route-level providers

    A configurable, persistent cart is now shared by the entire app. That's right for robot parts, but wrong for the Bot Squad: hired engineers land in the same cart as parts. A provider placed on a route creates an environment injector for that route and its child routes, so components under it receive their own service instances instead of the root ones. Here, you'll group the squad routes under one parent route, give that parent its own CartService and cart options, and then run the shop to see both carts in action. By the end of this step, the Bot Squad and Squad Roster pages share a cart that is saved separately from the parts cart. ### Parent routes with children

    A route can have a children array instead of a component. Each child's path is joined to the parent's, so a parent with path: 'admin' and a child with path: 'users' matches /admin/users. Grouping related pages under one parent gives you one place to attach settings that apply to all of them.

    {
      path: 'admin',
      children: [
        { path: 'users', component: UserListComponent },
        { path: 'roles', component: RoleListComponent },
      ],
    }
    ``` ### Route-level providers
    
    A route's `providers` array registers providers in a new injector for that route and its children. Listing a class there creates a new instance for that part of the app, and a token provider there overrides the root value for anything injected under the route. Because `CartService` reads its options with `inject()`, the instance created on the route picks up the route's options without any other changes.
    
    ```ts
    {
      path: 'admin',
      providers: [AuditService, { provide: THEME_TOKEN, useValue: { mode: 'light' } }],
      children: [/* ... */],
    }
    ``` ### Run the shop
    
    The shop needs two processes: the API server that serves the products, and the Angular dev server that serves the pages and forwards `/api` requests to the API server. Before its build output, the dev server prints a warning that it's a simple server that hasn't been reviewed for security issues. That's expected here, because the lab makes the dev server listen on every network address so your browser can reach it.
    
    In the first **Terminal**, confirm you're in the `application` folder, then run:
    
    ```bash
    npm run api
    

    You'll see API server listening on http://0.0.0.0:4000 in the terminal.

    Switch to the second Terminal, move into the application folder, then run:

    npm start
    

    You'll see Application bundle generation complete followed by the local address on port 4200.

    The Simple Browser should now display the webpage, but you may need to refresh it if it doesn't.

    The Catalog page lists products from the API. Buy a part on the Catalog page, and it appears on the Cart page but not on the Squad Roster page. Hire an engineer on the Bot Squad page, and it appears on the Squad Roster page but not on the Cart page. Refresh the page, and both carts keep their items. Well done: you've finished building Joe's Robot Shop on services.

    You moved the shop's product data into a root-provided service that loads typed data from the API, and you replaced each page's private cart with one signal-based CartService. In the running shop, you saw the parts cart and the squad cart fill up separately and survive a refresh.

    Along the way, you used inject(), signals, computed(), injection tokens, and route-level providers. You can apply the same approach to any Angular app: deciding where you provide a service controls whether the whole app shares one instance or a single section gets its own.

About the author

Pluralsight’s AI authoring technology is designed to accelerate the creation of hands-on, technical learning experiences. Serving as a first-pass content generator, it produces structured lab drafts aligned to learning objectives defined by Pluralsight’s Curriculum team. Each lab is then enhanced by our Content team, who configure the environments, refine instructions, and conduct rigorous technical and quality reviews. The result is a collaboration between artificial intelligence and human expertise, where AI supports scale and efficiency, and Pluralsight experts ensure accuracy, relevance, and instructional quality, helping learners build practical skills with confidence.

Real skill practice before real-world application

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Learn by doing

Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.

Follow your guide

All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.

Turn time into mastery

On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.

Get started with Pluralsight