Angular2如何覆盖提供者 [英] Angular2 How can I override provider

查看:116
本文介绍了Angular2如何覆盖提供者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Angular的新手,并且对提供者重写有疑问.我想在我的项目 https://www.npmjs.com/package/mydatepicker .

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.

我想重写该库的组件使用的语言环境提供程序.这是示例 https://plnkr.co/edit/fS8IoJqB8PYvgNEVGIMY .

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

我从库类(my.locale.service.ts)扩展了LocaleService,并希望使用它代替它,因此我在模块中指定了它:

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 }]

但是它不起作用,组件仍然使用它自己的LocaleService.我该如何实现?

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

谢谢!

推荐答案

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.

当Angular希望为该令牌注入服务时,它会创建并交付由第二个提供程序创建的实例.

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.

如果模块A为令牌'X'提供服务并导入模块B还提供了令牌"X"的服务,然后是模块A的服务定义获胜".

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".

由根AppModule提供的服务优先于导入模块提供的服务.AppModule总是赢.

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

如果您在 AppModule 中提供提供程序,则该提供程序将用于导入模块中提供的提供程序.

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

这与延迟加载的模块不同.如果在延迟加载的模块中提供了提供程序,则即使该模块和延迟加载的组件和服务也都在AppModule中提供,也会从该延迟加载的模块的提供程序中获取依赖关系.

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.

这篇关于Angular2如何覆盖提供者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆