Ionic2 ::在Modal页面中使用单例服务 [英] Ionic2 :: Using singleton service in Modal page
问题描述
我有一个应该是单身的服务,需要从多个视图访问。通过在 app.components.ts
中的 providers
数组中添加服务,我可以访问单个实例来自大多数页面的服务。
I have a service which is supposed to be a singleton and needs to be accessed from multiple views. By adding the service in the providers
array in app.components.ts
, I am able to access a singleton instance of the service from most pages.
但是,如果使用 ModalController
将组件作为模态加载,则会失败。它给了我没有提供XYZ
错误。
However, this fails if a component is loaded as a Modal using the ModalController
. It gives me the No provider for XYZ
error.
我需要做什么才能在里面使用单例服务由 ModalController加载的组件
?
What do I have to do to consume a singleton service inside a component loaded by ModalController
?
推荐答案
所以,我能够使其工作如下:
So, I was able to make it work as follows:
1。创建服务
@Injectable() export class MyService { ... }
2。在提供商
数组中的 app.module.ts
中添加服务
2. Add the service in app.module.ts
in the providers
array
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, MyService]
3。在任何 Page
或模态
3. Consume the service in any Page
or Modal
@Component(...)
export class MyModalOrPage {
constructor(public service: MyService) { ... }
}
Viola!单页服务实例可用于整个页面和模态。奇迹般有效! =)
Viola! Singleton service instance available throughout pages and modals. Works like a charm! =)
这篇关于Ionic2 ::在Modal页面中使用单例服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!