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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With