In Angular, the injector is a core part of dependency injection. What does it do?
Think about who is responsible for giving components the services they need.
The injector is responsible for creating and delivering service instances to components or other services that ask for them. It manages the lifecycle and sharing of these instances.
Consider a service provided in the providers array of a component. How does Angular handle this service instance?
Think about service scope and how providing in a component affects instance sharing.
When a service is provided in a component's providers array, Angular creates a new instance scoped to that component and its child components. Other parts of the app use different instances if they don't have their own providers.
Choose the correct way to inject a service named DataService into a component using Angular's constructor injection.
import { Component } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-example', template: '<p>Example works!</p>' }) export class ExampleComponent { constructor( /* injection here */ ) {} }
Remember how TypeScript and Angular use constructor parameters with access modifiers for injection.
Using private dataService: DataService in the constructor automatically creates and assigns the service instance to a private property. Option D misses the access modifier, so dataService is not stored as a property. Option D uses @Inject incorrectly without a parameter. Option D lacks the service type.
At what point does Angular create an instance of a service provided in the root injector?
Think about when Angular actually needs the service instance.
Angular creates service instances lazily. This means the instance is created only when something first asks for it, not before. This helps save resources.
Given this component code, why does Angular throw an error about MyService not being provided?
import { Component } from '@angular/core'; import { MyService } from './my.service'; @Component({ selector: 'app-test', template: '<p>Test works!</p>' }) export class TestComponent { constructor(private myService: MyService) {} }
Check how Angular knows where to get the service instance from.
Angular needs services to be provided either in a module or component providers array or declared with @Injectable({providedIn: 'root'}) to register them with the injector. Without this, Angular cannot create the service instance and throws an error.