Using services to decouple important info and functionality in an Ember app
Ember Services are objects whose information persists throughout different pages of the application. A common use of this is saving info about if a user is currently logged in and showing this across the site. It can also include lots of other functionalities that must be persisted, such as geolocation, third-party APIs, and server-backed events.
Services can be created with the Ember CLI like most other things. For user sessions, this could be done with ember g service session.
A simple version of this service would be:
Services can also include functions to better encapsulate all code related to a specific purpose. In this case, it’s all variables and functions related to logging in and out.
Services then need to be injected into controllers to be available in them and the views. Once injected, they can be accessed as normal.
You can then access the service value with ``, and also use these functions, in the view.
Using Store with Services
With EmberData, you can inject the store service and access database records the same way you would in a route. Remember that it returns a promise when setting a value to a variable.
Using Cookies with Services
Services don’t normally persist with page or browser refreshes. However the “ember-cookies” service add-on makes this easy.
If you want to check for cookies when the service is called, you should set this up in the init() function, shown below: