I have a very very large application with more than 50 modules that are lazy loaded. The problem is that @Injectable({ providedIn: 'root'}) will inject all my services in the root module(I guess, correct me if I am wrong).
How to lazy-load them? or since services are simple functions, doesn't it have performance side effects?
3 Answers
The problem is that @Injectable({ providedIn: 'root'}) will inject all my services in the root module(I guess, correct me if I am wrong).
Yes, it is provided in the module that was used to bootstrap the application. It does not matter where the file is physically located.
How to lazy-load them?
Stop providing them in the root.
doesn't it have performance side effects?
It has nothing to do with performance.
Place it in the root when it needs to be in the root, because it's a global service. Place it in a module when it's scope is only that module and it's imported children.
Leave it in the root if you don't understand why it should or should not be there.
Comments
If you want your service in all / most of your components in your feature module, then you need to use that service under feature module's providers. The benefit here is that, the same instance of a service is available to all your components in that feature module.
@NgModule({
providers: [yourService ]
})
export class featureModule {}
If you want to use your service specific to few of the components in your feature module then, inject your provider configuration in the component level.
@Injectable({ providedIn: 'root'})
By using the above metadata in the component level, it allows Angular to optimize an app by removing the service from the compiled app if it isn't used in that particular components.