Angular Js

Understand Angular's Providers & Injectors

Understand Angular's Providers & Injectors

Providers & Injectors

Providers & Injectors

Injectors
Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don't manually create an instance of the service. You inject the service and the dependency injection system takes care of providing an instance.
The use of dependency injection is not just for services. It may be used to inject (nearly) anything, including items found in the RouterModule like Routes.

Injectors are responsible of creating the objects to inject and injecting them in the components that request them. You tell injectors 'how to' create these objects by declaring a provider.
In the provider you can tell the injector to use a given value or use a class to instantiate

Injected objects are always singletons inside an injector but you can have more than one injector in your project.
They are created by Angular: A root injector is created in the bootstrap process and injectors are created for components, pipes or directives.
Each lazy-loaded module also gets its own.

You might require different instances of a given service in different modules or components.
For some services however you need to make sure that they are real singletons, meaning that there is only one instance in the whole application.


Providers
Providers for services are usually the service class itself and you would usually use the providedIn shortcut to provide the service in the root injector.


forRoot/forChild (Shared module)
Angular supports another way of importing a module with providers. Instead of passing the module class reference you can pass an object that implements ModuleWithProviders interface.


Suggested Readings
Explain Angular Modules or ngModule
What is Routing Module in Angular







Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram