0

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 3

1

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.

https://medium.com/@tomastrajan/total-guide-to-angular-6-dependency-injection-providedin-vs-providers-85b7a347b59f

Sign up to request clarification or add additional context in comments.

Comments

1

just don't pass to the decorator { providedIn: 'root'}.

Instead use @Injectable() for this service. And import the service into the necessary lazy-module and add it to the providers section.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.