Search code examples
angularvariablesserviceglobal-variablesbehaviorsubject

How to use a service variable


For a project, I need to retrieve data in realtime only once when I start the application and use the results of this request, from anywhere in the application.

So I assign the result to a service variable that I call on all pages.

Is this a good way to code?

Example I use:

exampleService.dataName

I had the idea to make a subject behavior in the service and to subscribe to this one in each page, however it makes me add subscribers and unsubscribe + creates a lot of variables in each page for the same result. Is my first method a good way?


Solution

  • using behavior subject is consider good practice when the data you store is changing during application work (e.g. one component changes the data and you need to know about the change instantly), when you subscribe to the behavior subject you instantly get the change. As you said, you have to unsubscribe when done (e.g. onDestory).

    If all you need is to retrieve the data once and it doesn't change throughout the application lifecycle, I would use a global parameter that is known to all components (maybe in your service component, or any other global component).