Skip to content

Instantly share code, notes, and snippets.

@alxhub
Created March 21, 2018 20:21
Show Gist options
  • Select an option

  • Save alxhub/38cae533189b475e866b8bdf148060d8 to your computer and use it in GitHub Desktop.

Select an option

Save alxhub/38cae533189b475e866b8bdf148060d8 to your computer and use it in GitHub Desktop.

What is the forRoot() method?

The forRoot() static method is a convention that makes it easy for developers to configure services and providers for a module which are intended to be singletons. For services it is preferable to specify providedIn: 'root' on the service's @Injectable(), which has the same effect.

... (rest)

Should I add application-wide providers to the root AppModule or the root AppComponent?

Application-wide providers should be defined by specifying providedIn: 'root' on their @Injectable() decorator (in the case of services) or at InjectionToken construction (in the case of tokens being provided). Providers created this way will automatically be made available to the entire application and don't need to be listed in any module.

If a provider cannot be configured in this way (perhaps because it has no sensible default value), then register it in the root AppModule, not in the AppComponent.

... (rest)

Should I add other providers to a module or a component?

Preferably, providers should be configured using @Injectable syntax (link). If at all possible, they should be provided in the application root (providedIn: 'root'). Services configured this way may still end up being lazily loaded if they are only used from a lazily loaded context.

If it's the consumer's decision of a provider whether it should be application-wide or not, then prefer registering providers in modules (@NgModule.providers) to registering in components (@Component.providers).

... (rest)

Providing a singleton service

There are two ways to make a service a singleton in Angular:

  • Declare that the service should be provided in the application root.
  • Include the service in the AppModule or in a module which is only imported by the AppModule.

Since Angular 6.0, the preferred way to create singleton services has been to specify on the service that it should be provided in the application root. This is done by setting providedIn to 'root' on the service's @Injectable decorator:

@Injectable({providedIn: 'root'})
export class UserService {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment