• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Destroy service for rxjs observables

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
? Implementation:
Here an on destroy service for being used in rxjs and angular component for unsubscribing observables.


@Injectable()
export class DestroyService extends Subject<void> {
ngOnDestroy() {
this.next();
this.complete();
}
}

? Question:
How Angular calls ngOnDestroy() in this pattern? Even though DestroyService is a service and extends Subject, how does Angular still invoke ngOnDestroy()?

? Answer:
Here's the key idea:

Even though DestroyService extends Subject (which is not a component or directive), Angular still calls its ngOnDestroy() method if the service is provided at the component level.
? Why ngOnDestroy() Gets Called in a Service

✅ Angular will call ngOnDestroy() if:

  • The class implements OnDestroy
  • AND it is a provider on a component or directive

Example:

@Component({
selector: 'app-foo',
providers: [DestroyService]
})
export class FooComponent {
constructor(private destroy$: DestroyService) {}
}

Then Angular treats the service like a directive-level provider, and because it has ngOnDestroy():
Angular will call that method when the component is destroyed.

? Why It Works Even Though It Extends Subject

  • Subject has no ngOnDestroy(). That's fine.
  • You're extending Subject and adding ngOnDestroy() yourself.
  • Angular doesn’t care that it extends Subject — it just sees:
    • “This class was provided in the component”
    • “It has ngOnDestroy()”
    • ✅ Call it when the component is destroyed

? Summary

  • DestroyService is a service, but it's scoped to the component using providers: [DestroyService]
  • It has a custom ngOnDestroy() method
  • Angular calls ngOnDestroy() on component-scoped providers
  • So you get an automatic, injectable "destroy notifier" for use with takeUntil()

This is a neat Angular trick that combines:

  • Lifecycle hooks
  • Dependency injection
  • RxJS

into a reusable, composable unsubscribe mechanism.
This is a neat Angular trick that combines:

  • Lifecycle hooks
  • Dependency injection
  • RxJS

into a reusable, composable unsubscribe mechanism.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу