Bird
0
0

You want to define a method in a generic Angular service that fetches data from an API and returns an Observable<T>. Which method signature correctly uses generics with Angular's HttpClient?

hard📝 Application Q8 of 15
Angular - TypeScript in Angular
You want to define a method in a generic Angular service that fetches data from an API and returns an Observable<T>. Which method signature correctly uses generics with Angular's HttpClient?
AfetchData(): Observable<T> { return this.http.get<T>(this.apiUrl); }
BfetchData(): Observable { return this.http.get(this.apiUrl); }
CfetchData<T>(): Observable<any> { return this.http.get(this.apiUrl); }
DfetchData(): Promise<T> { return this.http.get<T>(this.apiUrl).toPromise(); }
Step-by-Step Solution
Solution:
  1. Step 1: Use generic type parameter

    The service class is generic with type T.
  2. Step 2: HttpClient get method

    HttpClient's get<T> method returns Observable<T>, matching the generic type.
  3. Step 3: Correct method signature

    fetchData(): Observable<T> { return this.http.get<T>(this.apiUrl); } correctly returns Observable<T> and calls http.get<T>.
  4. Final Answer:

    fetchData(): Observable<T> { return this.http.get<T>(this.apiUrl); } -> Option A
  5. Quick Check:

    HttpClient generic get matches service generic type [OK]
Quick Trick: HttpClient.get() returns Observable [OK]
Common Mistakes:
  • Omitting generic type in HttpClient.get
  • Using Promise instead of Observable
  • Declaring method generic instead of class generic

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes