Component providers and the difference between module providers

What is the difference between the @Components providers and @Module providers property?

What are both worth?

EDIT

I have two components: LoginComponent and SigninComponent . On the other hand, I use UserService from the user library. This UserService service UserService looking for the opaquetoken BASE_PATH :

 @Injectable() export class UsersService { constructor(@Optional()@Inject(BASE_PATH) 

and BASE_PATH :

 export const BASE_PATH = new OpaqueToken('basePath'); 

This opaqueToken is installed in the AppModule:

 @NgModule({ bootstrap: [ App ], declarations: [ App, ErrorComponent ], providers: [ ENV_PROVIDERS, 

where ENV_PROVIDERS set according to the environment settings on environtment.ts :

 if ('production' === ENV) { enableProdMode(); PROVIDERS = [ ...PROVIDERS, // custom providers in production { provide: BASE_PATH, useValue: 'http://public.sample.com:8082/commty/cmng' } ]; } else { // Development PROVIDERS = [ ...PROVIDERS, // custom providers in development { provide: BASE_PATH, useValue: 'http://localhost:8082/commty/cmng' } ]; } export const ENV_PROVIDERS = [ ...PROVIDERS ]; 

I configure everything:

 @NgModule({ declarations: [ SigninComponent ], providers: [ UsersService ] }) export default class SigninModule { 

and

 @NgModule({ declarations: [ LoginComponent ], providers: [ UsersService ] }) export default class LoginModule { 

So, on components I do not import any Services as suppliers, I only declare them.

However, when I load SigninModule , my entire network request is sent to localhost . However, when I load LoginModule requests are sent to localhost:8282

+6
source share
2 answers

If you provide your service inside your component, it will be local. Therefore, if you have two instances of your component, you will have two instances of your service.

Now, if you provide your service inside your module, it will be global, and if you have two instances of your component, they will use the same service instance.

Tell me, if you do not understand, I will give you an example on the plunker.

+13
source

Quote from the official documentation:

On the one hand, the provider in NgModule is registered at the root of the injector. This means that every provider registered in NgModule will be available throughout the application.

On the other hand, a provider registered in an application component is available only for this component and all its children.

https://angular.io/guide/dependency-injection#when-to-use-ngmodule-versus-an-application-component

+2
source

Source: https://habr.com/ru/post/1014737/


All Articles