Injectable

From Get docs
< @angular/coreAngular/docs/11/api/core/injectable


Injectable

decorator

Decorator that marks a class as available to be provided and injected as a dependency.

Option Description
providedIn?

Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in one of the following injectors:

  • 'root' : The application-level injector in most apps.
  • 'platform' : A special singleton platform injector shared by all applications on the page.
  • 'any' : Provides a unique instance in each lazy loaded module while all eagerly loaded modules share one instance.

See also

Options

Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in one of the following injectors:

  • 'root' : The application-level injector in most apps.
  • 'platform' : A special singleton platform injector shared by all applications on the page.
  • 'any' : Provides a unique instance in each lazy loaded module while all eagerly loaded modules share one instance.

providedIn?: Type<any> | 'root' | 'platform' | 'any' | null

Usage notes

Marking a class with @Injectable ensures that the compiler will generate the necessary metadata to create the class's dependencies when the class is injected.

The following example shows how a service class is properly marked so that a supporting service can be injected upon creation.

@Injectable()
class UsefulService {
}

@Injectable()
class NeedsService {
  constructor(public service: UsefulService) {}
}

const injector = Injector.create({
  providers:
      [{provide: NeedsService, deps: [UsefulService]}, {provide: UsefulService, deps: []}]
});
expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);

© 2010–2021 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v11.angular.io/api/core/Injectable