Angular2 How can I override the provider?

I am new to Angular and wondering about dropping a provider. I would like to use this datepicker parameter in my project https://www.npmjs.com/package/mydatepicker .

I want to override the local provider that uses this library component. Here is an example https://plnkr.co/edit/fS8IoJqB8PYvgNEVGIMY .

I extended LocaleService from the library class (my.locale.service.ts) and want to use it instead, so I specified it in my module:

providers: [{provide: LocaleService, useClass: MyLocaleService }] 

But it does not work, the component still uses its own LocaleService. How can I achieve this?

Thanks!

+7
angular
source share
2 answers

https://angular.io/guide/ngmodule-faq#what-if-two-modules-provide-the-same-service

What if two modules provide the same service? When two imported modules loaded at the same time, list the provider with the same token, the second module provider wins. This is because both providers are added to the same injector.

When Angular tries to introduce a service for this token, it creates and provides an instance created by the second provider.

Each class that introduces this service receives an instance created by a second provider. Even classes declared in the first module receive an instance created by the second provider. This may be an undesirable surprise.

If module A provides a service for token "X" and imports module B which also provides a service for token "X", then for the service "Module A" the definition is "winning."

The service provided by the root AppModule takes precedence over the services provided by the imported modules. AppModule always wins.

If you provide the provider in the AppModule , this will be used for the providers provided in the imported modules.

This is different from lazy loadable modules. If the provider is provided in a lazy loaded module, the components and services lazy loaded by this module will become dependent on the lazy loaded module provider, even if it is provided in the AppModule.

+5
source share

It looks like your paths were imported incorrectly and your service file should be inside the src directory.

 import {MyDatePickerModule} from "mydatepicker/dist/my-date-picker.module"; import {LocaleService} from "mydatepicker/dist/services/my-date-picker.locale.service"; import {MyLocaleService} from "./my.locale.service"; 

See below working plunkr

https://plnkr.co/edit/e63S9dGXSc65BcKWMPnd?p=preview

+1
source share

All Articles