0

I am trying to make a single instance of a service available to all components in my app but some pages aren't getting the same one and instead instantiating their own. The app is a tabbed app and I think it is the tabs.module of the individual tab.module that is the problem.

I import the service in the app.module.ts:

import { InitiativeService } from './services/initiative.service';
...
providers: [InitiativeService]
...

And import it in each page that needs it: import { InitiativeService } from './services/initiative.service';

constructor(private initServive: InitiativeService) {}

Which works for every page except the tabs. There is a tabs.module.ts and each individual tab has it's own .module.ts file. Importing the service in there isn't solving the issue. The tab instances are still newly created instances of the service only available to them and their children.

Any help on exactly to do with the tab modules would be appreciated.

Steve
  • 1,903
  • 5
  • 22
  • 30
  • 1
    Injectable classes have a `providedIn` property, setting this to `root` will ensure it's a singleton. I assume `tabs.module` is declared as an import in the app.module correct? – Phix Apr 18 '20 at 00:47
  • Yes, tabs.module is in app.module. The service has the providedIn property already. – Steve Apr 18 '20 at 00:54
  • Set `providedIn: "root"` and remove the service from all `providers` lists. See [this answer](https://stackoverflow.com/a/36199007/1009922). – ConnorsFan Apr 18 '20 at 01:07
  • It should work then. Can you provide a reproduction? – Phix Apr 18 '20 at 01:09

0 Answers0