Dependency injection in tabs

New to ionic, intermediate level on Angular. . .
Normally in Angular I have only one root module “app.module.ts” where I declare my providers which are nicely injected throughout all the components.

I am trying to inject one and only one instance of a data service throughout all the tabs so that I can share data across the tabs.
I included this DataService in app.module.ts providers, but not sure how to pass it on to the other tabs?

Each tab is loaded in app-routing.module.ts, for example:
path: ‘home’,
loadChildren: () => import(’./components/home/home.module’).then( m => m.HomePageModule)

How do I do dependency injection across modules in this case?

Thank you!

IMHO this is a reasonable strategy, and it works perfectly well with Ionic apps. You’re not required to split everything into lazily-loaded modules. I don’t. There is just too much tedious boilerplate and opportunity for stupid wiring bugs like this, and not nearly enough benefit in ordinary, non-behemoth-sized apps.

You shouldn’t have to do anything special here. Services that are provided in the app module are associated with the root injector, and will be present in any other NgModules. Where it gets trickier is when you’re providing the service in a feature module.

So if you’re posting this as a preemptive question, my answer is “don’t worry about it”. If you’re posting it because something isn’t working as you expected, please post enough additional code for others to be able to reproduce your problematic behavior.

1 Like

Thanks very much!
I have done a few tests with a behaviorsubject(), I called next() in the app.module and when I switch tab I can see that the subject has an array of objects which proves that it is the same instance updated by the app.module. So Angular DI is more magic that I thought :slight_smile:, so in short this is not an issue as I thought.

Re lazily loading modules, I am doing that cause that’s the code that I got from running “ionic create” cli wizard and I simply thought there would be some good reason for it. I guess the only advantage would be a slightly faster startup depending on the complexity of the code, right?

I am going to ditch this pattern also because it’s not very readable and a bit spaghetti :smiley:

This is why I disagree so strongly with the Ionic team’s decision here. Everybody gets intimidated by the generators and cowed into accepting this choice to drastically complicate the structure of their app.

Yes, and depending on how much smarter webpack has gotten since I last dove deeply into the internals of all this (which, in fairness, was several years ago - you can start down the rabbit hole with ng-cli #2771), even that advantage may be mitigated by the code duplication incurred as overhead to support the whole lazy loading architecture.

Welcome to the resistance. :wink: