Ionic2 ::在Modal页面中使用单例服务 [英] Ionic2 :: Using singleton service in Modal page

查看:80
本文介绍了Ionic2 ::在Modal页面中使用单例服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应该是单身的服务,需要从多个视图访问。通过在 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屋!

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