Bird
0
0

Find the mistake in this service injection:

medium📝 Debug Q7 of 15
Angular - Services and Dependency Injection
Find the mistake in this service injection:
@Injectable({ providedIn: 'root' })
export class ApiService {
  fetch() { return 'data'; }
}
@Injectable({ providedIn: 'root' })
export class DataService {
  constructor(apiService: ApiService) {}
  getData() {
    return this.apiService.fetch();
  }
}
AApiService lacks @Injectable decorator.
BapiService is not declared as a class property, so this.apiService is undefined.
CDataService constructor should not have parameters.
Dfetch method should be async.
Step-by-Step Solution
Solution:
  1. Step 1: Check constructor parameter usage

    apiService is passed but not assigned to a class property with access modifier, so this.apiService is undefined.
  2. Step 2: Consequence in getData()

    Calling this.apiService.fetch() causes runtime error because this.apiService is undefined.
  3. Final Answer:

    apiService is not declared as a class property, so this.apiService is undefined. -> Option B
  4. Quick Check:

    Missing access modifier causes undefined property [OK]
Quick Trick: Add private/public to constructor param for property [OK]
Common Mistakes:
MISTAKES
  • Forgetting access modifier in constructor
  • Assuming parameter auto-assigns to class property
  • Thinking async is required for fetch method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes