Home >Web Front-end >JS Tutorial >An article to talk about dependency injection in Angular
This article will take you to continue learning angular and briefly understand dependency injection in Angular. I hope it will be helpful to you!
Translator added: Wikipedia points out - In software engineering, dependency injection (Dependency Injection, DI) refers to letting an object receive the dependencies it depends on of other objects. "Dependencies" refer to objects required by the receiver. "Injection" refers to the process of passing "dependencies" to the receiver. After "injection", the receiver will call the "dependency".
Translator added: For example - when
classA
uses some functions ofclassB
, it meansclassA
Has dependencies onclassB
. Before usingclassA
, we need to createclassB
. Recommended articleWhat is Dependency Injection? How to use it?
We all know the standard way of using services services
in Angular
. Mark the service as injectable and put it in the provider
section in the module. As follows:
For dependency injection, we have many tricks that we can use. For example, in the module Angular
you can convert a line TestService
to a different line of writing. [Recommended related tutorials: angular tutorial, Programming teaching]
We put it in the provider
section Each service is converted into an object with two properties. In the provide
attribute we can use the class name or we can create a unique key and inject an object. We can even inject a variable.
Another interesting feature is that we can inject multiple objects with the same key and use them like an array.
And, we can also inject different services according to different situations. In other words, we can use the if-else
statement.
Now, I hope you understand the charm of Angular
dependency injection.
If you want to learn more about the relevant code content, please click here.
This article is a translation, in the form of free translation. Original address: # Angular dependency injection
For more programming-related knowledge, please visit: Programming Video! !
The above is the detailed content of An article to talk about dependency injection in Angular. For more information, please follow other related articles on the PHP Chinese website!