0

Ever since digging past the first few basic levels of Angular dependency injection (DI), and striking the gem that is forRoot(), I have been wondering exactly what the best practices are for actually using it.

I stumbled across the method while in search of a way to allow a lazy loaded module to access a service within the root's context, allowing a stream of data to be shared between two modules, one or both of which may be lazy loaded. Since then I have wondered, could you use forRoot() for everything in a shared module and save a lot of import statements throughout an application? What are the catches? Are there certain things that are easily used in for root, and other things that aren't? Or was for root primarily developed to bridge the aforementioned DI context issue when bridging lazy loaded modules?

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
joshrathke
  • 7,564
  • 7
  • 23
  • 38
  • What do you mean "for everything in a shared module"? How would it save import statements? – Amit Jul 25 '17 at 06:45

2 Answers2

8

The purpose of forRoot() is to have singleton services in the application.

The meaning of the forRoot() is to have only one instance of the service which was exported by that ModuleWithProviders. Without the forRoot() if you have added a service in the module's providers and use that module in many places, you can have many instances of that service in the different layers of your application. With forRoot() , it will create a new instance of a service, if the last was not found anywhere.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • This is the confirmation I was looking for. I had heard rumblings that it could be used to pull in more than services, but didn't really see any concrete evidence. – joshrathke Jul 26 '17 at 00:07
1

The forRoot static method is just a convention for configure the module's providers.

for example: RouterModule.forRoot: You pass the routes to forRoot method in order to configure the app-wide Router service with routes.

Create a SharedModule with the components, directives, and pipes that you use everywhere in your app.

The SharedModule should not have providers for reasons explained here. Nor should any of its imported or re-exported modules have providers. If you deviate from this guideline, know what you're doing and why.

Shlomi Levi
  • 3,114
  • 1
  • 23
  • 35