Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Components providers and Module providers difference

Tags:

angular

Which's the difference between @Components providers property and @Module providers?

What do both stand for?

EDIT

I've two components: LoginComponent and SigninComponent. By other hand I'm using an UserService from a custom made library. This UserService service is looking for an opaquetoken BASE_PATH:

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

and BASE_PATH is:

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

This opaqueToken is set on AppModule:

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

where ENV_PROVIDERS is set according environtment 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'm setting up all:

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

and

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

So, on components, I don't import any Service as providers, I only declare them.

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

like image 915
Jordi Avatar asked Feb 06 '17 15:02

Jordi


2 Answers

Quoting from official documentation:

On the one hand, a provider in an NgModule is registered in the root injector. That means that every provider registered within an NgModule will be accessible in the entire application.

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

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

like image 163
Mariano Roberto Medina Avatar answered Sep 22 '22 18:09

Mariano Roberto Medina


If you provide your service inside your component, it will be local to it. So if you have two instance of your component, you will have two instance of your service.

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

Tell me if you don't understand, I will provide you an example on plunker.

like image 32
Maxouhell Avatar answered Sep 19 '22 18:09

Maxouhell