I need a good example of using a service singleton as data source for my Angular 2 application.
Scenario is as following:
I have an application that is loading prices of some items from the local database (in my case MongoDB). A few of the components need to use a service which will be the universal source of truth for item prices throughout the application. These prices can be acted upon externally: user can change currency, so they have to be recalculated, or can change the date range for which price averages will be calculated.
So I need to have a singleton service which will load upon app initialization and components need to load prices only after the service data store has been initialized with prices. Also, components need to refresh data(I guess using Observable pattern) when, say, the currency or date range has been changed. Perhaps the best way is to inject the service in the app
component, so it gets initialized first?
Is there a recipe or proposed architecture for this kind of app?
I can't call some init function from each component with ngOnInit()
because I want data available in multiple components. I need to know in each component when to initialize it with data from Service's data store. I need to know when data is ready.
The way I did it in Angular 1.x is to instantiate the service, and in constructor initialize data, and then when the data is initialized, emit a $rootScope
event to tell all components that data is ready.
I can't find a proper recipe to do the same thing in Angular 2.