AweSIM
AweSIM

Reputation: 1703

Ionic2 :: Using singleton service in Modal page

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.

However, this fails if a component is loaded as a Modal using the ModalController. It gives me the No provider for XYZ error.

What do I have to do to consume a singleton service inside a component loaded by ModalController?

Upvotes: 2

Views: 520

Answers (1)

AweSIM
AweSIM

Reputation: 1703

So, I was able to make it work as follows:

1. Create a service

@Injectable() export class MyService { ... }

2. Add the service in app.module.ts in the providers array

providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, MyService]

3. Consume the service in any Page or Modal

@Component(...)
export class MyModalOrPage {
    constructor(public service: MyService) { ... }
}

Viola! Singleton service instance available throughout pages and modals. Works like a charm! =)

Upvotes: 1

Related Questions