SoFunction
Updated on 2025-04-04

Angular design pattern hierarchical injector realizes code reuse modularity

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 oneLoggerServiceUsed to record the application's log information. You can apply the root moduleAppModuleThis service is provided in:

import { LoggerService } from './';
@NgModule({
  providers: [ LoggerService ],
  ...
})
export class AppModule { }

so,LoggerServiceIt becomes a singleton service, and there will only be one in the entire application.LoggerServiceExample. 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 subcomponentsLoggerServiceExample. 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,SomeSpecificComponentInjected into all its subcomponentsLoggerServiceIt will be this new instance, not inAppModuleSingletons 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!