Angular có injector hierarchy: root/environment injector, route injector và element/component injectors.
Cleanup theo đúng scope bằng DestroyRef:
@Injectable()
export class RouteScopedStream {
private destroyRef = inject(DestroyRef)
start() {
interval(1000).pipe(takeUntilDestroyed(this.destroyRef)).subscribe()
}
}Provider ở scope càng thấp thì càng nhiều instance được tạo và bị destroy theo lifecycle của scope đó.
Đây là lợi thế để cô lập feature state, nhưng nếu service giữ subscription/timer/WebSocket mà không cleanup thì leak theo route hoặc component.
Angular has an injector hierarchy: root/environment injector, route injectors and element/component injectors.
Clean up at the correct scope with DestroyRef:
@Injectable()
export class RouteScopedStream {
private destroyRef = inject(DestroyRef)
start() {
interval(1000).pipe(takeUntilDestroyed(this.destroyRef)).subscribe()
}
}The lower the provider scope, the more instances are created and destroyed with that scope lifecycle.
This is useful for isolating feature state, but if a service holds subscriptions, timers or WebSockets without cleanup, it can leak at route or component scope.