The Spotyngular Project: Part 5 – Services & Routing
This is the sixth post of “The Spotyngular Project” series of posts. Throughout this series, we are cloning spotify with AngularJS 2 to expose this framework’s benefits and tricks. We started our first post by talking about the basics of Angular JS 2, then we set up the environment, we got started with the demo and focused on the structure. In the previous post we went over thesyntax of AngularJS 2 templating feature and now we’ll be creating a service and implementing routing.
In this post we will create an example service that will
retrieve data from the database. We did it before with the
MusicStrip component but we know it is not good to access
data from within a Component, so we will create a layer of
abstraction to access the data using this service.
We
will also see how to implement routing in AngularJS 2. To do
so we will be routing from a card to a playlist.
Services
Creating a service
A service in AngularJS 2 is a simple class. We don’t have a factory, a service, a value, a constant, etc anymore. We will have a single class that represents a service.
An example of the service we want to implement is:
There are some things to point out here.
First, every class except the class of the root
component is marked as an export, we need
to do that so as to import it in other modules.
Second, the @Injectable annotation. When
we used Http in MusicStrip we only imported
the modules and then we used it in the
BrowseMusicStrip class.
And that occured because MusicStrip is a child
component, and if we addhttpInjectables
to the bootstrap function in the root
component all the child components can access http.
That is not the case of a service, because a service
is not a child component. Therefore to ensure
AngularJS resolves the type when the application runs,
we need to specify the annotation
@Injectables. And voila, with this we
will have a service working in AngularJS 2.
Using a service
Now we need to know how to use a service. There are two ways: