Angular – Services

On the last section, we talked about the different types of Directives. In this article, 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.

services

  • 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.

services

  • 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.

  • 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.

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].

services

You’ve then 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’.

services

  • 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.

services

And that is how services are created and used. On the next article, we will discuss how to create and use routes.

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.