NG.IV · Angular 22 practice question

A developer needs to conditionally instantiate a service implementation based on an environment flag read during injection. Which dependency injection mechanism should they employ to achieve this dynamic instantiation?

import {inject, InjectionToken, Service} from '@angular/core';

@Service({
  factory: () => (inject(ANALYTICS_ENABLED) ? new GoogleAnalytics() : new Analytics()),
})
export class Analytics { /* ... */ }
Choose one answer
Check answer and explanation

Correct answer: Using the `factory` option on the service metadata, which allows reading other dependencies via `inject()` within the factory function.

Explanation

The `factory` option allows the developer to execute a function that can use `inject()` to check environment tokens and return the appropriate class instance, fulfilling the requirement for conditional instantiation.

Common trap

The `useFactory` option is part of `@Injectable` but the source explicitly states that `factory` replaces the use of `@Injectable` options like `useFactory` when custom instantiation logic is needed.

Source: Angular docs: Creating and using services — Replacing the implementation with a factory
Checked against the cited text on 2026-11-25.

Report an error in this question