In this section, we will be discussing Services. They are simple classes that provide data in our application.
There are two ways to create Services: either create it manually or via Angular-CLI.
Let us try creating it manually. In your file explorer under the src/app folder, create a new file.

1

  • Go to src/app and then right click
  • Click the New File and you’ll be asked for a filename

Let’s name the file stock.service.ts.

2

  • Basic format of naming a file is “[myServiceName].[fileType].ts” and in this case I named it ‘stock’

Services fish data from from either a web service or any data source. Open the newly created file and we’ll make a very basic service class.

3

  • First we need to import {Injectable} from angular/core.
  • Next we added an Injectable Decorator.

In our export class StockService, let us now define the data source of our Service. We will use a set of names using an array of strings.

4

And there you have it – you have just manually created a Service!
Next, we will create another using the angular-cli. Again, let’s open our integrated terminal and type the command ng g service [serviceName].

5

Congratulations! You’ve successfully created a Service manually and via Angular-CLI.
Now we’ll learn how to use them. Services are made to provide data. So in here, it is needed in our stocks.component.ts to inject data to our unordered list ‘stock’.

6

7

  • Import our {StockService} from the file stock.service and remove the .ts extension
  • ‘Stocks’ variable draws data from the array in StockService class.

Save your work and run the app. Go to your integrated terminal and type ng serve. Go back to your browser and the output should look like this.

8

On the next article, we will discuss Creating and Using Routes.

 

 

 

JOIN THE ANGULAR ACADEMY!
$100,000 is the average annual salary of talented software developers and your chances of getting this salary get better by learning Angular 2 today!

Sign up now and make the first step towards upgrading your skill set.

PLUS: Get up to 75% OFF our Angular 2 course in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.