Skip to content
Advertisement

Angular 7 shared service is not shared

I am new to angular and I am trying to pass data from one component(HomeComponent) to another component(ProfileComponent) after navigation.

I created a shared service(DataService). I injected the service in both the HomeComponent and ProfileComponent but when I set the value of the message property in HomeComponent and try to retrieve it in the ProfileComponent the value is undefined because the DataService is not the same instance.

The DataService was registered in the AppModule in the providers array so it should be a shared service and always the same instance right?

Thanks in advance

DataService.ts

JavaScript

HomeComponent.ts

JavaScript

ProfileComponent.ts

JavaScript

AppModule.ts

JavaScript

Advertisement

Answer

Each time you inject the service to your component, new instance is generated. However in this case i would recommend you to use BehaviorSubject as follows,

JavaScript

STACKBLITZ DEMO

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement