skip to Main Content

Just need some clarification on documentation of takeUntilDestroyed operator, so reading this doc: https://angular.io/api/core/rxjs-interop/takeUntilDestroyed , I dont see any words that I should use takeUntilDestroyed without params only in "injection" context (I dont really know what does this means). So basicly "Otherwise, the current DestroyRef is injected." so I can use it every where in component, directive, service, etc.

So question is this documentation is not fully describe how injection happens or it is problem with me?

(Please dont put any link explaining how this operator works, I know exactly how it works and checked source code, question is about documentation understanding)

2

Answers


  1. The injection context is explained in this doc. Basically, it’s a runtine context where a current injector is set and Angular is able to use for dependency injection.

    takeUntilDestroyed requires an DestroyREf to schedule the observable completion. this can be done 2 ways:

    • rely in DI to get it, that the default behaviour and uses inject(DestroyRef). inject requires of course an injection context
    • Pass DestroyRef as argument, so no injection context is required.
    Login or Signup to reply.
  2. In code:

    class SomeComponent {
      // this is in an injection context
      someService = inject(SomeService);
      destroyRef = inject(DestroyRef)
    
    
      constructor() {
        // this is in an injection context
    
        obs$.pipe(
          takeUntilDestroyed() // destroyRef not needed
        ).subscribe(() => {
          ...
        })
      }
    
      ngOnInit() {
        // this is NOT in an injection context
      }
    
      someMethod() {
        // this is NOT in an injection context
    
        obs$.pipe(
          takeUntilDestroyed(this.destroyRef) // destroyRef needed
        ).subscribe(() => {
          ...
        })
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search