Creating a Service

In this lesson, we’ll cover store services and how to create them.

Tuning

Our next mission is to make the list of bands reactive. Creating a new band should update the list of bands in the sidebar.

Services: useful singletons

In the Controllers chapter, you learned that controllers are singletons. It was more of a hindrance than a feature because controllers are closely bound to UI state, and most of the time, you want UI state to be cleared when you move away from the page that piece of UI is rendered on.

There are other kinds of states in most, non-trivial applications. For example, you might want to retain data as you move between pages of your application, which is not related to your domain models. We can call this an application state. A typical example is maintaining a session that holds the current user.

As in most situations, the framework has us covered. Services are baked into the framework for this exact reason.

The current task at hand, storing existing bands and songs, seems like a fitting use case. If we had a store that can hold our bands and songs and defined methods on the store for access, we’d be able to overcome the problem of the model hooks being too rigid.

Building a store… I mean, a catalog

The first step is to create the store service. For reasons revealed later, we’ll choose a different name for our service and we’ll call it “catalog.” Our catalog will hold the bands and songs we create in the application.

We can generate a service with Ember-CLI using the following command:

ember g service catalog

Note: We have already created the service mentioned above. You can type this command in the terminal widget below, and you can also try creating services with different names.

Get hands-on with 1200+ tech skills courses.