Angular's "dependency injection"
Angular's "dependency injection" is a design pattern that helps us organize and share code more efficiently. In Angular, we can reuse and modularize code by injecting services (a common type of injectable object) into components, directives, or other services.
Angular's injector system is hierarchical, also known as "hierarchical injector". This means you can create and inject services at different levels, which determines their scope of action and shared behavior.
How it works
For example, suppose you have oneLoggerService
Used to record the application's log information. You can apply the root moduleAppModule
This service is provided in:
import { LoggerService } from './'; @NgModule({ providers: [ LoggerService ], ... }) export class AppModule { }
so,LoggerService
It becomes a singleton service, and there will only be one in the entire application.LoggerService
Example. You can inject this service anywhere you need:
import { LoggerService } from './'; @Component({ ... }) export class SomeComponent { constructor(private logger: LoggerService) { ('Hello World!'); } }
However, sometimes you may want to use a separate one in a particular component and its subcomponentsLoggerService
Example. At this time, you can provide it in the metadata of that component.LoggerService
:
import { LoggerService } from './'; @Component({ providers: [ LoggerService ], ... }) export class SomeSpecificComponent { constructor(private logger: LoggerService) { ('Hello Specific World!'); } }
in this case,SomeSpecificComponent
Injected into all its subcomponentsLoggerService
It will be this new instance, not inAppModule
Singletons provided in .
This is how Angular's "hierarchical injector" works. Each injector has a parent injector. When you try to inject a service in a component, Angular will first look for the service in the component's injector. If it is not found, it will look for it in the parent injector, and this process will continue until the root injector. If the service is not found throughout the process, Angular will throw an error.
The above is the detailed content of the Angular design pattern hierarchical injector to implement code reuse and modularization. For more information about Angular hierarchical injector, please pay attention to my other related articles!