Angular 22 Introduces injectAsync() to Lazy Load Services on Demand
Angular 22 has introduced a new injectAsync() API that allows developers to load services dynamically only when they are actually needed, rather than including them in the initial JavaScript bundle. This is particularly useful for rarely used features that depend on large third-party libraries, such as PDF or spreadsheet generators. Instead of returning the service directly, injectAsync() returns a function that resolves the service on first call and reuses the same promise on subsequent calls, avoiding redundant downloads. The API requires services to be auto-provided, either via the @Injectable({ providedIn: 'root' }) decorator or the newer @Service() decorator. Angular also supports a prefetch option using onIdle, which allows the browser to download the lazy dependency during idle time so users experience no delay when they eventually trigger the feature.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in