Error Encyclopedia

Injector has already been destroyed

This error occurs when you attempt to retrieve a service from an injector that has already been destroyed. This typically happens when code tries to access dependencies after a component, directive, or module has been destroyed.

Common scenarios

Accessing services in callbacks after destruction

When a component is destroyed, its injector is also destroyed. If an async callback later tries to access services, this error occurs:

@Component({  /*...*/})export class UserProfile implements OnInit {  private userClient = inject(UserClient);  ngOnInit() {    setTimeout(() => {      // ERROR: If component was destroyed before timeout fires,      // the injector is no longer available      this.userClient.fetchData();    }, 5000);  }}

Accessing services after unsubscribing

Similar issues occur with observables if cleanup happens in the wrong order:

@Component({  /*...*/})export class DataView implements OnDestroy {  private dataStore = inject(DataStore);  ngOnDestroy() {    // Problematic: attempting to use the injector during destruction    // after other cleanup may have occurred    this.dataStore.cleanup();  }}

Debugging the error

To fix this error:

  1. Check async operations — Ensure callbacks, promises, and subscriptions are cancelled when the component is destroyed. Use takeUntilDestroyed() or DestroyRef for cleanup.

  2. Capture dependencies early — Store references to services in class fields rather than accessing the injector in callbacks.

  3. Guard against destroyed state — For operations that might outlive the component, check if the component is still active before accessing services.

@Component({  /*...*/})export class UserProfile implements OnInit {  private destroyRef = inject(DestroyRef);  private userClient = inject(UserClient);  ngOnInit() {    // Use takeUntilDestroyed to automatically cancel when destroyed    interval(5000)      .pipe(takeUntilDestroyed(this.destroyRef))      .subscribe(() => {        this.userClient.fetchData();      });  }}

The stack trace indicates where the destroyed injector was accessed. Work backwards to identify the async operation that outlived its component.