0
votes

I've got a service that gets instantiated twice with Angular 8.
It is declared with provided in: 'root' on the service decorator.
It only happens when I inject the service to the top component and another one.
The other components can call each other so I have a hierarchy like the following:

Top Component
Component1
Component2
Component1
Component3
Component2

If I inject the service in component1 and component2, I don't have any issue
If I inject the service in Top Component,Component1 and component2, the service gets instantiated twice (1 for the Top Component and 1 for the others). This service helps me communicate between components. So the instances of components 1 & 2 can communicate but since the Top Component has its own service, it can't receive any info from the other components.

2 other piece of information:
- I don't have this issue when using production mode (for now I am working locally with ng serve in development mode)
- If I remove the provided in: 'root' and declare the service in the root @NgModule,

1) if I inject the service in component1 (for example), it works fine
2) if I inject the service in Top Component, I have an injection error stating no provider for...

I see that the service is instantiated twice by putting a console.log in the constructor (btw the console.log does not appear on the same line for the 2 instances, one of the service seems to be transpiled first, so the console.log is not executed at the same line) console log at new instance

I can't replicate the error in a new angular project

Sorry I can't post any specific code. Any clue of what's going on or could be happening, will be appreciated! Thanks

1
Can you show a stackblitz? - Eliya Cohen
I can't replicate the error in a basic angular project and I can't show my actual project. Not sure what I could show in a stackblitz unfortunately. - Eric Mallard

1 Answers

0
votes

Ok, so deconstructing the project and the faulty component brick by brick I found the culprit:
import { SomeService } from 'src/app/services/some-service.service.js';

Seems harmless enough, when you look quickly. It's weird because I'm pretty sure it's an auto import from Angular, but notice the .js at the end? Well, since the initial file is a .ts, it seems it was transpiling it to Javascript and treating it as another service. It's a pretty specific issue, but I post the answer just in case anyone runs into it. Removing the .js clears the problem.