Bird
0
0

What is wrong with this Angular observable subscription code?

medium📝 Debug Q14 of 15
Angular - RxJS and Observables Fundamentals
What is wrong with this Angular observable subscription code?
this.data$ = this.http.get('/api/data');
this.data$.subscribe(data => {
this.data = data;
});
this.data$.subscribe(data => {
console.log(data);
});
AThe subscribe method is misspelled.
BMultiple subscriptions can cause repeated HTTP calls.
CObservables cannot be assigned to variables.
DThe HTTP get method does not return an observable.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze multiple subscriptions to the same observable

    Each subscription to an HTTP observable triggers a new HTTP request, causing repeated calls.
  2. Step 2: Identify the problem in the code

    Here, this.data$ is subscribed twice, so two HTTP requests are sent, which is inefficient and often unwanted.
  3. Final Answer:

    Multiple subscriptions can cause repeated HTTP calls. -> Option B
  4. Quick Check:

    Multiple subscriptions = repeated HTTP calls [OK]
Quick Trick: Avoid multiple subscriptions to HTTP observables [OK]
Common Mistakes:
MISTAKES
  • Thinking subscribe is misspelled
  • Believing observables can't be variables
  • Assuming HTTP get returns non-observable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes