Home >Web Front-end >JS Tutorial >An article to talk about dependency injection in Angular

An article to talk about dependency injection in Angular

青灯夜游
青灯夜游forward
2023-01-06 21:14:252124browse

This article will take you to continue learning angular and briefly understand dependency injection in Angular. I hope it will be helpful to you!

An article to talk about dependency injection in Angular

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 of classB, it means classA Has dependencies on classB. Before using classA, we need to create classB. 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:

An article to talk about dependency injection in Angular

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]

An article to talk about dependency injection in Angular

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.

An article to talk about dependency injection in Angular

Another interesting feature is that we can inject multiple objects with the same key and use them like an array.

An article to talk about dependency injection in Angular

And, we can also inject different services according to different situations. In other words, we can use the if-else statement.

An article to talk about dependency injection in Angular

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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete