Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk3 min

How to Create and Inject a Service in Angular

Create a reusable Angular service, inject it into components or other services, and choose the provider scope that gives it the right lifetime.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create a TypeScript class for reusable behavior, register it with Angular’s dependency-injection system, then inject it where needed. The right decorator and provider scope depend on your Angular version and whether the service should be shared across the app or limited to a particular consumer.

What an Angular service does

Angular describes services as “reusable pieces of code that you can share across your application.” A service is a good place for behavior such as data access or business logic that would otherwise be duplicated across components. Keep its purpose focused so consumers can use it without depending on unrelated implementation details.

As an Amazon Associate I earn from qualifying purchases.

Angular’s current unversioned guide uses @Service() as the root-provided shorthand. The Angular v20 guide documents the established @Injectable({ providedIn: 'root' }) form. Follow the documentation for the version of Angular your project uses; the available documentation does not establish a release boundary for @Service.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create the service

Generate a service with the Angular CLI

From your Angular workspace, run the CLI command shown in the Angular guide:

ng generate service CUSTOM_NAME

Replace CUSTOM_NAME with a name for the service. The CLI creates a dedicated TypeScript file; edit the generated class to implement the behavior your app needs.

Write a service manually

You can also create a TypeScript file and define the class yourself. This example follows the current unversioned guide’s @Service() style:

import { Service } from '@angular/core';

@Service()
export class BasicDataStore {
  private data: string[] = [];

  addData(item: string): void {
    this.data.push(item);
  }

  getData(): string[] {
    return [...this.data];
  }
}

The v20 guide’s common root-provided form uses @Injectable instead:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class BasicDataStore {}

Both examples mark a class for Angular’s dependency injection. Do not combine decorator patterns without checking the guide for your project’s Angular version.

Inject the service into a consumer

In current Angular examples, use inject() in a valid injection context, such as a component or service field initializer:

import { Component, inject } from '@angular/core';
import { BasicDataStore } from './basic-data-store';

@Component({
  selector: 'app-example',
  template: '<p>Items: {{ store.getData().length }}</p>'
})
export class ExampleComponent {
  protected readonly store = inject(BasicDataStore);
}

The same pattern works when one service depends on another. With the current @Service() approach, use inject() for dependencies. Constructor injection remains documented in versioned guidance and is a reason to use @Injectable rather than the current @Service shorthand.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose where Angular provides the service

Provisioning determines which injector can supply the service and whether consumers share an instance. Root provision is the usual choice for application-wide behavior; local providers are useful when a consumer needs its own instance or a narrower lifetime.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Provider location or setup What it means When to use it
@Service() or @Injectable({ providedIn: 'root' }) Provides the service at the application root. When consumers across the application should use the root-provided service.
A component’s providers array Associates a provider with that component’s injector, allowing a component-specific instance. When that component’s subtree needs its own instance.
A route or application-level provider configuration Registers providers in that configuration’s injector scope. When the service should be available within the configured route or application scope.
@Injectable() without automatic provision Marks the class for DI but does not by itself register it with an injector. When you intend to register it explicitly in the relevant providers configuration.

Angular also supports provider definitions such as useClass, useValue, useExisting and useFactory for cases requiring more configuration than a class decorator alone. For dependencies that are not classes—such as a configuration value, function or primitive—use an InjectionToken so Angular has a unique token to resolve; a token can also define a factory for automatic provision.

Troubleshoot injection errors

  • Provider not found: A class decorated with @Injectable() but lacking automatic provision must be registered in the appropriate providers array. Check that the provider is registered in a scope visible to the consumer.
  • inject() called outside an injection context: Use it in a valid context, such as a field initializer or constructor, rather than an arbitrary method or function call.
  • Unexpectedly separate instances: Check for a provider in a component or other local scope. A local provider can create a scoped instance instead of relying on the root-provided one.
  • Version or decorator mismatch: Confirm the syntax against the Angular documentation matching your project version, particularly when choosing between @Service() and @Injectable.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.