Using `takeUntilDestroyed()` outside injection context

Discussão em 'Angular' iniciado por Adassko, Novembro 19, 2024.

  1. Adassko

    Adassko Guest

    I see all examples (such as https://stackoverflow.com/a/76264910/2770274) that uses takeUntilDestroyed outside injection context to use injected DestroyRef like the following:

    export class Component implements OnInit {
    destroyRef = inject(DestroyRef);

    ngOnInit() {
    this.service.getData()
    .pipe(takeUntilDestroyed(this.destroyRef))
    .subscribe();
    }
    }


    I think it would be a little neater and need less imports to just call the function in the constructor and pass the resulting OperatorFunction where needed:

    export class Component implements OnInit {
    takeUntilDestroyed = takeUntilDestroyed();

    ngOnInit() {
    this.service.getData()
    .pipe(this.takeUntilDestroyed)
    .subscribe();
    }
    }


    Looking at the implementation of the function (https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/src/take_until_destroyed.ts) I see no problems with this approach, am I missing something?

    Continue reading...

Compartilhe esta Página