Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are providers in Angular2?

In the Angular2 component configuration providers is one of the keys that we could specify. How are these providers defined and what are they used for?

@Component({   ..   providers: [..],   .. }) 

Note:

Angular2 documentation is gradually maturing but still sparse. It currently defines providers as:

An array of dependency injection providers for services that the component requires.

This recursive definition isn't very helpful. A more detailed explanation with an example would really help.

like image 473
Pranjal Mittal Avatar asked Jun 16 '16 19:06

Pranjal Mittal


People also ask

What are providers in NG module?

providers: Creators of services that this NgModule contributes to the global collection of services; they become accessible in all parts of the app. (You can also specify providers at the component level, which is often preferred.)

What does Providers mean in Angular?

A provider is an instruction to the Dependency Injection system on how to obtain a value for a dependency. Most of the time, these dependencies are services that you create and provide. For the final sample application using the provider that this page describes, see the live example / download example .

What are providers in Angular 8?

A provider is an object declared to Angular so that it can be injected in the constructor of your components, directives and other classes instantiated by Angular.

What are the types of providers in Angular?

There are four ways by which you can create the dependency: They are Class Provider (useClass), Value Provider (useValue ), Factory Provider ( useFactory ), and Aliased Class Provider ( useExisting).


1 Answers

Providers are usually singleton (one instance) objects, that other objects have access to through dependency injection (DI).

If you plan to use an object multiple times, for example, the Http service in different components, you can ask for the same instance of that service (reuse it). You do that with the help of DI by providing a reference to the same object that DI creates for you.

@Component){   ..   providers: [Http] } 

..instead of creating new object every time:

@Component){} class Cmp {   constructor() {     // this is pseudo code, doens't work     this.http = new Http(...options);   } } 

This is an approximation, but that's the general idea behind Dependency Injection - let the framework handle creation and maintenance of reusable objects... Provider is Angular's term for these reusable objects (dependencies).

like image 66
Sasxa Avatar answered Oct 02 '22 15:10

Sasxa