So in my app.component contains the header on every page (CoreModule imported in app.module) as well as an app-routing.module that loads modules based on routes (SomeContainerRoutingModule in this case)
The problem is when I try to import the DropdownComponent which is part of the CoreModule into the container, it treats the Subject as a separate object and doesn't include the Observables as the ones found in the header. When I exclude the CoreModule from the imports the Subject works fine, but the DropdownComponent is no longer on the page.
How can I use the same Subject/service while also adding the core component to the page? Shouldn't CoreModule already be imported from the root app.component that the header resides on?
CoreModule
...
declarations: [HeaderComponent, DropdownComponent],
providers: [MessageService]
export class CoreModule {}
SomeContainerRoutingModule
...
imports:[...
//CoreModule
//removing this makes Subject work. Adding it makes the component appear
...
MessageService
export class MessageService {
private subject = new Subject<any>();
sendMessage(message){this.subject.next(message);}
getMessage(){return this.subject.asObservable();}
}
I've tried adding the core component to the imports of the container module but I get Error: Type DropdownComponent is part of the declarations of 2 modules: CoreModule and SomeContainerRoutingModule!.... I've also tried adding the service to the container module but it doesn't seem to affect anything.
Seems that you want your MessageService to be singleton in your app.
In this case it's better not to provide it anywhere, and just add providedIn: 'root' in your MessageService @Injectable decorator, like this:
@Injectable({
providedIn: 'root'
})
export class MessageService {
private subject = new Subject<any>();
sendMessage(message){this.subject.next(message);}
getMessage(){return this.subject.asObservable();}
}
Then it will be provided in all your components, and it will be singleton. Just make sure you remove MessageService from all modules provider arrays (don't provide it in core module or anywhere else). Otherwise, if you provide it in some lazy module, like your SomeContainerRoutingModule most likely, then this module will have its own injector for that service, and it will create a new instance.
Here's very detailed documentation on how dependency injection works in angualr: https://angular.io/guide/hierarchical-dependency-injection