Bird
0
0

What is wrong with this Angular service code using HttpClient?

medium📝 Debug Q14 of 15
Angular - HTTP Client
What is wrong with this Angular service code using HttpClient?
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class ApiService {
  constructor(private http: HttpClient) {}

  fetchData() {
    return this.http.get('https://api.example.com/items').subscribe(data => {
      console.log(data);
    });
  }
}
ACalling subscribe inside the service instead of returning Observable
BMissing import of HttpClientModule in app module
CHttpClient.get URL is invalid
DNo error, code is correct
Step-by-Step Solution
Solution:
  1. Step 1: Analyze how HttpClient is used in the service

    The service method calls subscribe inside itself, which is not recommended because it hides the Observable from the component.
  2. Step 2: Best practice for HttpClient usage

    Services should return the Observable and let components subscribe, enabling better control and testing.
  3. Final Answer:

    Calling subscribe inside the service instead of returning Observable -> Option A
  4. Quick Check:

    Subscribe belongs in component, not service [OK]
Quick Trick: Subscribe in component, not inside service method [OK]
Common Mistakes:
MISTAKES
  • Subscribing inside service instead of returning Observable
  • Ignoring HttpClientModule import (not shown here)
  • Assuming URL format causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes