Store a global variable from ajax call

I have a list of years in an array format [2018, 2019, 2020] that is returned from my back end. Right now, i’m using a setup controller to make the ajax call and set it as a value to be used by my ember-power-select. However, I just need this to be done once, like on application load and have it as a global variable, instead of everytime the controller loads since this array will rarely change.

How should I go about this ?

Devinda

You can make a Service and store whatever “global” things you want on it. So that is one option.

Alternatively, if you’re already using ember-data, it’s already providing a service that does caching (the store), so you could make a model that represents the list of years and load that via ember-data.

In either case, you can choose to deal with the asynchrony in your routes (by awaiting a promise in the model hook that ensures the data is loaded), or you can deal with it down at the component level. The tradeoff is that doing it in the routes lets you write simpler components that can just synchronously access the data, while doing it in the components keeps the data loading closer to the data usage, at the cost of having more complex behaviors (components need to know how to render loading & error states on their own).

5 Likes