Injectable

decorator

Marks a class as available to Injector for creation.

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 the 'root' injector, which will be the application-level injector in most apps.

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 the 'root' injector, which will be the application-level injector in most apps.

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

Usage notes

The following example shows how service classes are properly marked as injectable.

@Injectable()
class UsefulService {
}

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

const injector = ReflectiveInjector.resolveAndCreate([NeedsService, UsefulService]);
expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);

Injector throws an error if it tries to instantiate a class that is not decorated with @Injectable, as shown in the following example.

class UsefulService {}

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

expect(() => ReflectiveInjector.resolveAndCreate([NeedsService, UsefulService])).toThrow();

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