A Model component DI issue?

hi there,
I’m building an app right now, what I try to achieve is a singleton service for the whole app, and my strategy is to provide the service in the root component (app.module) and never provide it to the children components, so the angular DI will only use the service instance from the root component and never create new one.

So I create new service for caching. This service should be a singleton, thus I only provide it to the app.module

//app.module.ts
@NgModule({
declarations: [

],
imports: [

],
bootstrap: [IonicApp],
entryComponents: [

],
providers: [CachService] // <— here I provide the service
})

then in each page I just import this service and then use it without adding it to the providers list, so the page with will not create a new instance of this service . .

everything works very well, and I use the singleton service on every page now .

The problem occurs when I use “Model component”, every time I create and present a model, it creates a new instance of my caching service .

here an example …

let modal = this.mc.create(SomePage, this.user);
modal.present();

  • the SomePage uses the caching service and it should only uses a caching service instance provided by the parent component (app.module) , but when I present the model a new caching service instance created !!

But if I don’t use the model and use the navigation controller to push this page,
this.nv.push(VeriCodePage);
it works as expected, no new caching service instance .

is this a bug in the model component ? or my implementation is wrong ?

to test this you can add console.log in the constructor and see how many console.log you get .

in angular2 I never have this kind of problems, because the Angular DI will take care of it, if you really know how DI works. But Ionic2 act wired !! I believe there is some issue with the model component implementation.

but here a quick fix to this problem .
basically, I implement the Singleton design pattern .

// SingletonService.ts
class SingletonService {
static service: Singleton   = null

  getService() {
    if(SingletonService.service)
        return SingletonService.service = new SingletonService();
     else
        return SingletonService.service
    }
}

and the most important thing is to provide a factory to this service.

// app.module 
....
@NgModule({
  declarations: [
   ....
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
      .....
  ],
  providers: [{
      provide: SingletonService,
       useFactory: () => {                          <<---- this is our factory 
            SingletonService.getService()
        }
   }]
})

please let me know if there is another way to fix this issue