Modals annd tabs create new instances for services


#1

I am converting an application that load components from side menu to the use of @ionicPage. In my application I load components in a modal that use a service but from the declaration of the module for the ionic page, the component that opens in the modal create new instances of the services instead of using those declared in the page. Any ideas?

Thank you


#2

You are using lazy loading? Have a look where you provided your providers. If you register them in app.module.ts the instance will be the same for the all app, if you register them in a module, the instance will be the same for the module and submodule

app.module.ts

providers: [
  DummyProvider
]

=> one instance of DummyProvider for your app

vs

app.module.ts

providers: [
]

yourModule.module.ts

providers: [
  DummyProvider
]

=> one instance of DummyProvider for this module and not for the all app


#3

Thanks a lot. Yes, i’m using lazy load. Services are injected in the page Module, would be right. The problem occurs when the component is created by Ionic in tabs and modals.


#4

Have you try inject them in app.module.ts only once there and remove the injection in your pages/components/etc.?


#5

@jromerob If the page in the modal is in a lazy loaded chunk (javascript generated file) that is different than the one from your first page, the service will have different instances.

For now, stick to including all your services in AppModule to avoid problems like that (there will be only one service instance of that type in the entire app).

In Angular 6 you can avoid all that with providedIn: root, so you won’t need to import singleton services in any module anymore and they won’t be included in the initial bundle (main.js) if they are used only in lazy loaded modules:

https://angular.io/guide/singleton-services#providing-a-singleton-service

This is both great both in terms of performance as well as maintenance.

Angular 6 will work only with Ionic 4 (still in alpha) tough.


#6

This is a descripction of the error, i think the injections are right. The problem comes when Ionic create the component for the modal or into Tabs. Ionic create the component and create a new instance, the same component in template, no throught modal works right with the service


#7

Could you provide this (your diagram/app) as repo/code?

Why using a ServiceModule, would you like to give a try to remove this module and put your services in app.module.ts instead?