Matthias Müller
Matthias Müller

Reputation: 3473

How are Modules and Components saved internally?

Regarding the Angular2-Practices, it is recommended to put the declarables, which are used on multiple other Modules, into a shared one. It is furthermore strongly recommended to not set any provider on such a shared-module. Instead, if the shared Module has services together with declarables, a static method called forRoot should be added, which returns a ModuleWithProviders-Object and only gets called by the app-Module. I see the reasoning behind this: Since every lazy-loaded Module has its own Dependency Injector, every subequently loaded Module would get checked for its providers and used on the lazy Module instead of an application-wide Service. What I don't see here:

Since the Angular2-Logic only scans for declarables known by the Module, the comon sense would tell us to make smaller, compact shared Modules. Yet, since almost every Module has services and therefore has to be loaded by the app-Module AND each consumer, there has to be some sort of trade-off.

Upvotes: 2

Views: 81

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657506

  • Services often are not stateless, they are often used to share state between components, and if it's only a shared observable that one component or services uses to send events to another. There is does matter if there is one or more instances.

Modules are very lightweight. The forRoot() in a lazy loaded module only registers providers eagerly, the rest of the module is still lazy.

  • I don't know about the reasons for the suggestions forRoot() in CoreModule.

Upvotes: 1

Related Questions