kdocs
GitHub
Lang - Web
Lang - Web
  • Base
    • Css
    • Javascript
    • Typescript
      • New Project
  • Frameworks
    • Angular
      • Directives
      • Components
      • Templates
        • Bindings
        • Control Flow
        • Variables
      • Signals
      • Pipes
      • Services
        • Dependency Injection
      • Forms
        • Reactive Form
        • Template-Driven Form
      • Router
      • HTTP Client
      • Observables RxJS
      • Testing
        • Components
        • Directives
        • Pipes
        • Services
      • Optimization & Performance
      • Security
Powered by GitBook
On this page
  • Generate Service (CLI)
  • Best Practices
  • Examples
  • Circular Dependencies
  • forwardRef()
  1. Frameworks
  2. Angular

Services

PreviousPipesNextDependency Injection

Last updated 5 months ago

ng g service [service-name] [options]

Best Practices

  • Services are Singleton, do use services as singletons within the same injector.

    • Use them for sharing data and functionality.

  • Single Responsablility, create services with a single responsability.

    • Think about every component or service that injects it, and the weight it will carry.

Examples

First step is to add the @Injectable decorator to show that the class can be injected.

// For local level services - available to the Component (USING ElementInjector)
@Injectable()
export class LocalService { ... }

// Or

// For root level services - available everywhere (USING root EnvironmentInjector)
@Injectable({
    providedIn: "root",
})
export class SomeService { ... }

After Angular creates a new instance of a Component, or directive, or pipe class, it determines which service or other dependencies that class needs by looking at the constructor parameter types.

Accessing the service inside a component can be done by:

  • Either declaring it in the Component constructor.

  • Or by using inject(). (Newer way)

@Component({
    providers: [LocalService]
})
export class Component {
    // Declare it in the constructor
    constructor(private someService: SomeService, private localService: LocalService) {}

    // Or by calling `inject()`
    private someService = inject(SomeService);
    private localService = inject(LocalService);

    someFunction() {
        this.someService.serviceMethod();
        this.localService.serviceMethod();
    }
}

Circular Dependencies

forwardRef()

There will be times when an class A refers to class B, but class B also refers to class A, or when a class C makes a reference to itself.

This classical problem lies on how one of them will be defined first.

Angular forwardRef() function resolves this since it creates an indirect reference that Angular can resolve later.

@Component({
    providers: [
        {
            provide: PARENT_MENU_ITEM,
            useExisting: forwardRef(() => MenuItem),
        },
    ]
})

Generate Service (CLI)