injectLazy
is a helper function that allows us to lazily load a service or any kind of Angular provider.
Lazy loading services is useful when we want to shrink the bundle size by loading services only when they are needed.
Usage
injectLazy
accepts a function that returns a Promise
of the service. The function will be called only when the service is needed.
It can be a normal dynamic import or a default dynamic import from a module.
Then, we can use injectLazy
to lazily load the service.
We can also use injectLazy
not in an injection context, by passing an injector to it.
Testing
In order to test the lazy injected service we can mock them using mockLazyProvider
.
Testing Example
Let’s test the below component
In our test file we can do this:
Now the component will use the mocked version of the service.