Search code examples
angulardependency-injectionangular2-templateangular2-services

Singleton service - different values for its attributes in multiple components


I want to have a shared state/data between two components (topic component and topic-detail component). I decided to use a singleton injectable service (topic service) for this.

The behaviour is as follows: If the user clicks on a row from the table (see pic1), onSelect method is called (see pic2), and it sets to topic service the selected topic(which is that row).

The topic service uses setSelectedTopic (see pic3) method to set the data/state for the selected topic/row.

In the TopicDetailComponent (see pic5) the topic service is injected, and when I try to access in ngOnInit method, the attribute this.topicService.selectedTopic, I get 'undefined', even though the correct topic is passed to service.

So the problem is when the topic service passes selectedTopic to TopicDetailComponent ngOnInit, the this.topicService.selectedTopic is undefined.

Can someone help me with this problem?

Thank you!

P.S. I'm new to Angular 2, so please bear with me :)

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here


Solution

  • I think you should completely remove the providers from topics.component.ts if you want the Service to be a singleton. If you specify the TopicService as a provider it will create a new instance of the service and you will lose the singleton behaviour.