Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 How can I override provider

Tags:

angular

I'm new to Angular and have a question regarding provider overriding. I'd like to use this datepicker in my project https://www.npmjs.com/package/mydatepicker.

I want to override locale provider this library's component uses. Here is example https://plnkr.co/edit/fS8IoJqB8PYvgNEVGIMY.

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

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

But it doesn't work, component still uses it's own LocaleService. How can I achieve this?

Thank you!

like image 557
igor Avatar asked Jan 16 '17 22:01

igor


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 a provider with the same token, the second module's provider "wins". That's because both providers are added to the same injector.

When Angular looks to inject a service for that token, it creates and delivers the instance created by the second provider.

Every class that injects this service gets the instance created by the second provider. Even classes declared within the first module get the instance created by the second provider. This can be an unwelcome surprise.

If Module A provides a service for token 'X' and imports a module B that also provides a service for token 'X', then Module A's service definition "wins".

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

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

This is different for lazy loaded modules. If a provider is provided in a lazy loaded module, components and services lazy loaded by this module will get the dependency from the provider of the lazy loaded module, even when it's provided in AppModule as well.

like image 90
Günter Zöchbauer Avatar answered Sep 18 '22 13:09

Günter Zöchbauer


Your paths seem to be imported wrongly and your service file needs to 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

like image 33
Evans M. Avatar answered Sep 22 '22 13:09

Evans M.