Let’s suppose we have an application with a lazy-loaded submodule.

Both our main module and the submodule depend on a counter service, located in a third module.

We can see this scenario running on this plunkr.

When we browse from the root route to the lazy-loaded one, counters do not match!

Although the example is a bit simple, maybe we were thinking both modules were going to receive the same instance of the SubModule2Service service when actually it’s going to be instantiated once for each module.

This is where forRoot comes in. If we want our service to be unique and to be instantiated only once, there’s a convention for that.

That convention consists of creating an static method called forRoot. This method will return a ModuleWithProviders interface and must be only called by the main module. The returned object should include all services that we consider transverse to the application and that should be instantiated only once.

So it’s so easy to adapt the previous example to keep an only instance of the counter. We can see it working on this link.

Angular’s RouterModule is a great example for this use case, and it’s well explained in the How To Use section from the docs.

Anuncios