Bird
0
0

Identify the error in this Angular component code:

medium📝 Debug Q14 of 15
Angular - RxJS and Observables Fundamentals
Identify the error in this Angular component code:
export class DataComponent implements OnInit {
  data$ = this.service.getData();

  ngOnInit() {
    this.data$.subscribe(data => {
      console.log(data);
    });
  }
}

What is the main problem here?
AObservable should not be assigned to a property
BSubscription syntax is incorrect
CMissing unsubscribe in ngOnDestroy causes memory leak
DngOnInit should not contain subscriptions
Step-by-Step Solution
Solution:
  1. Step 1: Check subscription management

    The code subscribes to an Observable but never unsubscribes, risking memory leaks.
  2. Step 2: Lifecycle hook missing unsubscribe

    Without ngOnDestroy to unsubscribe, the subscription stays active even after component destruction.
  3. Final Answer:

    Missing unsubscribe in ngOnDestroy causes memory leak -> Option C
  4. Quick Check:

    Always unsubscribe to avoid leaks [OK]
Quick Trick: Always unsubscribe in ngOnDestroy to prevent leaks [OK]
Common Mistakes:
MISTAKES
  • Thinking subscription syntax is wrong
  • Believing Observables can't be class properties
  • Assuming ngOnInit forbids subscriptions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes