Lazy Load Services in Angular

Netanel Basal
Netanel Basal
Published in
2 min readAug 9, 2022

Imagine we have a large service with many dependencies and logic. It should only be used when a user performs a specific action, such as clicking a button.

It’s possible to defer the loading and parsing of the service by lazy loading it when the action is performed.

Let’s create a lazy inject service:

The get() method expects a provider token loader — a promise that returns a provider token. A reference to the provider is retrieved from the injector when the provider is loaded. Let’s use our service:

And that’s all. We can take it one step further. Imagine we have several strategies and need to choose one based on configuration. Each strategy contains a lot of code. Adding every strategy to the main bundle would be wasteful since all clients would have to download and parse it, even if they didn’t need it.

We can lazy load the required service in runtime and make it available to our component through the injector. Let’s see a simple example of using a storage provider:

All files under storage directory

Now we can create a directive that’ll lazy load the required service based on a configuration, create an injector, and pass it to the component:

MyComponent doesn’t care about the implementation details. It injects the Storage token and uses it.

Follow me on Medium or Twitter to read more about Angular and JS!

--

--

Netanel Basal
Netanel Basal

Written by Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.

Responses (10)