Skip to content

Dependency Injection

Daniel Bolin edited this page Feb 6, 2023 · 1 revision

Intro

Angular 14 introduced a new function called inject as an alternative way of DI.
Going forward you should use this function and the patterns described in the examples below instead of declaring dependencies in the constructor's parameters.

Examples

Basic usage

✅ Do:

class MyComponent {
  readonly service = inject(Service);
}

❌ Don't:

class MyComponent {
  constructor(readonly service: Service) { }
}

Better typings for InjectionToken

✅ Do:

const MY_TOKEN = new InjectionToken<string>('token');

class MyComponent {
  readonly value = inject(MY_TOKEN); // Type of `string` is inferred
}

❌ Don't:

const MY_TOKEN = new InjectionToken<string>('token');

class MyComponent {
  constructor(
    @Inject(MY_TOKEN) readonly value: number // Whoops! Wrong type not caught
  ) { }
}

✅ Do:

class MyComponent {
  readonly optionalService = inject(Service, { optional: true }); // Type is `Service | null`
}

❌ Don't:

class MyComponent {
  constructor(
    @Optional() readonly optionalService: Service // Whoops! Maybe null if not found
  ) { }
}