Angular · Middle · Question 21 of 75

What is the modern way to unsubscribe from an Observable when a component is destroyed?

constructor() {
  interval(1000).pipe(takeUntilDestroyed()).subscribe((n) => this.tick.set(n));
}

Explanation

It uses DestroyRef under the hood. Called without arguments it needs an injection context; elsewhere pass a DestroyRef. HTTP requests complete by themselves, but interval, valueChanges and router events don't.

Further reading

Problem with a question

Angular · Middle · question 21

Test yourself

Take the Angular · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz