When you write a shared module for your application, that contains stuff you use in other modules in the same app, you typically want all the services in that module shared only once.
If you just put the services in the
providers property of the shared module’s
NgModule() decorators, you might get weird cases, especially with lazy loading, when it feels like there’s more than one instance of the service. This is bad if you want to have shared state.
So, there is a better way to write your shared modules:
forRoot() pattern / convention is very common in libraries, and you’ll see it in things like ng-bootstrap and others. The name isn’t special for the compiler / framework, but it’s a common pattern.
When using these, in the
imports section you can just import the module itself (which gives you any
declarations needed like directives etc), and in the
exports use the
forRoot() version of the module so that it’s available for consumers of your shared module.
Then in your other application modules you can add
SharedModule to their
imports normally, except for the
AppModule will be the only place where you add
Then in your
AppModule, import it as:
There is one exception to this though. Your tests.
If you are writing any unit tests where you are importing the
SharedModule, you will probably need to import the module with its providers, because there is no
AppModule in the test.
And of course let me know if you have any questions / problems.
How did I learn that?
As a bonus for coming here, I'm giving away a free newsletter for web developers that you can sign up for from here.
It's not an anything-and-everything link list. It's thoughtfully collected picks of articles and tools, that focus on Angular 2+, ASP.NET (4.x/MVC5 and Core), and other fullstack developer goodies.
Take it for a test ride, and you may unsubscribe any time.
You might also want to support me by checking these out [Thanks]: