3

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.

Miloš Stanić
  • 460
  • 1
  • 6
  • 13

1 Answers1

2

You need to create a service and define it when bootstrapping your application:

bootstrap(App, [ SingletonService ]);

This way you will have a single instance for the whole application.

If you want to initialize things, you can use it constructor. To notify other elements that use the service, you can use one or several properties of EventEmitter. This way you will be able to emit events when data are there or when something changes. Components could subscribe on these EventEmitters to be notify...

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • This is kind of the scenario I had in mind. Do you perhaps have a link of some article or example with such scenario? Thanks. – Miloš Stanić Feb 29 '16 at 13:20
  • 1
    I think that this question could interest you: http://stackoverflow.com/questions/34376854/delegation-eventemitter-or-observable-in-angular2/34402436#34402436 – Thierry Templier Feb 29 '16 at 14:03
  • I finally got to implement the solution using the example you linked above. And it works. Maybe you should incorporate the link in your main answer, as I already marked it as correct. Thanks. – Miloš Stanić Mar 01 '16 at 12:22