Bird
0
0

How can you ensure cleanup of a subscription created in ngOnInit to avoid memory leaks in Angular?

hard📝 Application Q9 of 15
Angular - Components
How can you ensure cleanup of a subscription created in ngOnInit to avoid memory leaks in Angular?
ANo need to unsubscribe if using ngOnInit
BUnsubscribe inside ngOnInit lifecycle hook
CUnsubscribe inside constructor
DUnsubscribe inside ngOnDestroy lifecycle hook
Step-by-Step Solution
Solution:
  1. Step 1: Identify when to clean subscriptions

    Subscriptions should be cleaned when the component is destroyed to avoid leaks.
  2. Step 2: Use ngOnDestroy for cleanup

    ngOnDestroy is the lifecycle hook designed for cleanup tasks like unsubscribing.
  3. Final Answer:

    Unsubscribe inside ngOnDestroy lifecycle hook -> Option D
  4. Quick Check:

    Cleanup subscriptions in ngOnDestroy [OK]
Quick Trick: Unsubscribe in ngOnDestroy to prevent leaks [OK]
Common Mistakes:
  • Unsubscribing too early
  • Ignoring unsubscribe
  • Trying to unsubscribe in constructor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes