Bird
0
0

What is wrong with this service usage in a component?

medium📝 Debug Q14 of 15
Angular - Services and Dependency Injection
What is wrong with this service usage in a component?
@Injectable({ providedIn: 'root' })
export class DataService {
  data = [];
}

@Component({ selector: 'app-test', template: '' })
export class TestComponent {
  dataService: DataService;
  constructor(private dataService: DataService) {
  }
}
AService should be injected, not created with new
BDataService must not have data property
CComponent must not have constructor
DService must be provided in component, not root
Step-by-Step Solution
Solution:
  1. Step 1: Identify service instantiation method

    The component creates a new service instance manually using new, bypassing Angular's injector.
  2. Step 2: Understand Angular DI pattern

    Services should be injected via constructor parameters to get the singleton instance managed by Angular.
  3. Final Answer:

    Service should be injected, not created with new -> Option A
  4. Quick Check:

    Inject services via constructor, not new [OK]
Quick Trick: Never use new for services, always inject [OK]
Common Mistakes:
MISTAKES
  • Creating service instances manually
  • Ignoring Angular dependency injection
  • Misunderstanding providedIn usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes