Lazy Load Services
-
Lazy Load Services
-
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.
@Injectable({ providedIn: 'root' })
class LazyInject {
constructor(private injector: Injector) {}
async get<T>(providerLoader: () => Promise<ProviderToken<T>>) {
return this.injector.get(await providerLoader());
}
}
import type { BigService } from './big-service.service';
@Component({
template: `
<button (click)="doSomething()">Action</button>
`
})
export class FooComponent {
constructor(private lazyInjector: LazyInject) {}
async doSomething() {
const service = await this.lazyInjector.get<BigService>(() =>
import('./big-service.service').then((m) => m.BigService)
);
service.doSomething()
}
}