• Overview
@angular/core

injectAsync

function
stablesince v22.0

A helper function that allows to inject dependencies asynchronously, which can be useful in cases when the dependency is not needed immediately and can be loaded lazily.

API

function injectAsync<T>(
  loader: () => Promise<ProviderToken<T>>,
  options?: InjectAsyncOptions | undefined,
): () => Promise<T>;

Description

A helper function that allows to inject dependencies asynchronously, which can be useful in cases when the dependency is not needed immediately and can be loaded lazily.

NOTE: To enable lazy loading, the injected service must be auto-provided. This means it should be decorated with either @Injectable({providedIn: 'root'}) or @Service().

Usage Notes

class MyCmp {
 someSvc = injectAsync(() => import('..'));

 async onClick() {
   (await this.someSvc()).handleClick();
 }
}

// we can also configure prefetching:
injectAsync(.., {prefetch: onIdle})
Jump to details