Q1. What is dependency injection in Angular?
Dependency injection (DI) is a design pattern where a class receives its dependencies from an external source rather than creating them itself. Angular has a built-in DI framework that provides dependencies to components, services, and other classes. It promotes loose coupling, testability, and reusability.
Q2. How does Angular''s DI work?
Angular creates an injector hierarchy. When a component requests a dependency, the injector looks for a provider at the component level, then walks up the hierarchy. Providers tell Angular how to create the dependency. The @Injectable decorator and provider configurations define the resolution rules.
Q3. What are the different ways to provide a dependency?
1. @Injectable({ providedIn: ''root'' }) - at service level. 2. providers array in @Component - component-level instance. 3. providers array in @NgModule - module-level instance. 4. Using @Inject and InjectionToken for non-class dependencies. 5. Using useClass, useExisting, useValue, useFactory for custom providers.
Q4. What is the @Inject decorator used for?
@Inject is used to specify a provider token when the type is not enough, such as for primitive values or interfaces. It''s often used with InjectionToken. Example:
export const API_URL = new InjectionToken(''api.url'');
constructor(@Inject(API_URL) private apiUrl: string) {}
Q5. What is the hierarchical nature of DI in Angular?
Angular has multiple injectors: NullInjector, platform injector, root injector (for @Injectable({providedIn:''root''})), and component injectors (for providers in components). Each component can have its own injector that inherits from its parent. This allows different instances of a service at different component levels.
