This article will give you a detailed introduction to the dependency injection mode in Angular. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Dependency Injection: Dependency Injection is referred to as DI
In development, you will often encounter the instantiation of objects. When there are dependencies between multiple objects, manual instantiation will be particularly troublesome.
If an object A depends on object B, then object A does not need to explicitly instantiate the B object. B will be injected by an external mechanism. Object A only needs to declare a B object. This is the problem that dependency injection solves.
Another concept that often appears together with dependency injection is called Inversion of Control.
Inversion of Control: Inversion of Control, referred to as IOC, refers to the reversal of dependent control from the inside of the code to the outside of the code.
Dependency Injection and Inversion of Control are two sides of the same coin, expressing one idea. Dependency Injection focuses on describing the means, that is, how to achieve control inversion, Control Inversion focuses on describing the purpose, that is, the purpose is to reverse the control of dependencies from the inside of the code to the code external.
Related tutorial recommendations: "angular tutorial"
Each component has an injector instance, which is responsible for injecting the objects required by the component. The injector is a service class provided by Angular. Under normal circumstances, there is no need to call the injector method directly. The injector will automatically inject the objects required by the component into the component through the component's constructor(constructor). The provider tells the injector how to create the instance.
In order for the injector to know how the injected object is instantiated, the provider needs to be specified. Generally, we will pass the providers attribute of the component or module. Declare the objects that need to be provided.
providers:[{provide:AService, useClass: AServivce}] <=> providers:[AService] provide 属性:指定了提供器的令牌(token) useClass 属性:表示实例化方式是 new
使用 useFactory 方式实例化对象 providers:[ { provide:AService, useFactory: (bService: BService) => { .... }, deps:[BService] //deps声明工厂方法所依赖的服务。 ] 工厂方法创建的对象是单例对象
Object declared in the constructor (constructor), The token in the providers will be matched based on the class name, and then the specified object will be instantiated based on the value of the useClass attribute.
For more programming-related knowledge, please visit: Programming Video! !
The above is the detailed content of Detailed explanation of dependency injection pattern in Angular. For more information, please follow other related articles on the PHP Chinese website!