Angular 2 Services

If a piece of code is needed by many components in our application. A good practice is to create a single reusable service.

When a component needs this service we can simply inject it (the service).

angular 2 services example

let’s discover what’s a service

angular 2 service

try the live example Yourself.

try angular 2 service

A service is the mechanism used to share functionalities over Components (or with one Component if our app contains only one Component)

As you may already know, we can create Components in angular 2 and nest multiple Components together with selectors. Once our Components are nested we need to manipulate some Data and maybe this Data is not just a variable within our Component. Or we want to do some calculations.

In real life Data comes from Server. (e.g. JSON file)

Service is the best way to handle this.

Service is the best place from where we can bring our external Data to our app. Or do some repetitive task or calculations.

Service can be shared between as many as Components we want.

Or maybe you want to share other things (functionalities) over multiple Components or Portions of your app? The answer is : Service

angular 2 services – build our example

let’s build our example / Solar System Planets

First we create a class Planet (as instance we will have Earth, Mars, Jupiter … )

This will make our (service) classinjectable in other components in our application.

We can now get an instance of our Service Class in another Class.

Inside our service we have a method called getPlanets(). We use inside this method a promise to return the value of PLANETS.

In this chapter we explain just the Service; you can check other tutorials on: angulartypescript.com.

We adopt this approach to make it easy to understand each part independently.

call / inject the service

In our main component we inject the service using the provider property in @

File: planets-list.component.ts

In this example we use nested components, we have already explained what it means in a previous tutorial, so it will be easy for you understand. We have a planet component; we call this component inside another component planets-list component.

Please check the live example to get the code related to the planet component.