Return to site

Injection de dépendance

Way to supply a new instance of a class with the fully-formed dependencies it requires

· angular

The documentation on Angular defines dependency injection (DI) as, “a way to supply a new instance of a class with the fully-formed dependencies it requires. Most dependencies are services. Angular uses dependency injection to provide new components with the services they need.”

Essentially it is a mechanism in which the components of you Angular application resolve any dependencies related to services or components required by your component.

As you progress through the course, these concepts will be explored more fully along with examples of implementations in code to give you hands-on practice and reinforce your understanding.

Introduction to Dependency Injection (DI)

Dependency Injection (DI) is a software design pattern that manages how components in a system obtain their dependencies. In Angular, Dependency Injection is responsible for:
• Creating components
• Maintaining a component's state
• Providing components to other components, as required
In Angular, DI allows us to share variables and functions between self-contained modules without having to reuse code, and maintains the state of each component.
DI employs the injector, the service object(s) to be used, the client object that is depending on the services it uses, and the interfaces.

Using Dependency Injection

In order to understand how to use DI, and to gain a better understanding of DI itself, we'll use a scenario where we discuss how to make a service available to a component in your Angular application. You will be creating a service in the lab for this module and using DI to access the service.

In our lab scenario, we will be creating an interface to some data that will come from GitHub. We are building a GitHub search component for the lab. This interface will be used in a service and that service will become an injectable component available for use in other components.

In the last lab step in this module, you will inject that service into your application module and use it to access the functionality of the Git search. In this way, our service is a stand-alone, testable, and reusable component but not only that, we don't need to worry about instantiating it in our client code. Angular takes care of this for us automatically. An added benefit is that the service may contain data that becomes shareable among all components that inject it. It is a singleton.

 

This diagram depicts the integration of the various components.

broken image

To use a service