AppDividend
Latest Code Tutorials

Angular Service Example | Angular 8 Service Guide

3

Angular Service Example is today’s leading topic. We are using Angular 8 for this tutorial. Components should not fetch or save data directly, and they indeed shouldn’t knowingly present fake data. They should focus on representing data and delegate data access to a service. 

If you are new to Angular then please check out my these tutorials.

  1. Angular Router Tutorial Example

  2. Angular Form Validation Example

  3. Angular Dependency Injection Example

Angular Service Example

Content Overview

Services in Angular are a great way to share information among classes that do not know each other

When we are developing an Angular app, we will most likely run into a scenario in which we need to use the same code across multiple components. In that case, Services will help us to get rid of this problem. We can share the services code among various components.

We should not violate some general programming principles like Single Responsibility Of a Class.

In this case, Components use to display and present the data. Services use to fetch the data from the API. Let us get started our Angular 8 Service Example.

Step 1: Install Angular via CLI.

You need to set up a dev environment before you can do anything.

Install Node.js® and npm if they are not already on your machine.

 Then install the Angular CLI globally.
npm install -g @angular/cli

Step 2. Create a new project.

Type the following command.

ng new ngservices

Step 3: Serve the application.

Go to the project directory and launch the server.

cd my-app
ng serve --open

Step 4: Create a Service class.

To create an angular service class, at the console, type the following command in your root of the folder.

ng g service crypto

It will create the following files.

  1. crypto.service.ts
  2. crypto.service.spec.ts

Now, import the service file into the app.module.ts file.

import { CryptoService } from './crypto.service';

@NgModule({
  providers: [CryptoService], 
})

Now, we need to add some code to the crypto.service.ts file. This file contains the data that we need to consume. So this is a service file. In the Live project, this file will hit the GET or POST request to the server and insert or fetch the data. So this file provides services from frontend to backend.

// items.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class CryptoService {

  coins= [
    {id: 1, name: 'BTC'},
    {id: 2, name: 'XRP'}
  ];

  constructor() { }

  getMyItems()
  {
    return this.coins;
  }

}

Step 5: Use services into the component.

So your app.component.ts file looks like this.

// app.component.ts

import { Component } from '@angular/core';
import { CryptoService } from './crypto.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  coins = [];
  constructor(private cryptoservice: CryptoService)
  {
    this.coins = cryptoservice.getMyItems();
  }
}

Also, we need to update the HTML as well.

<table>
  <tr>
    <th>ID</th>
    <th>Name</th>
  </tr>
  <tr *ngFor="let coin of coins">
    <td>{{coin.id}}</td>
    <td>{{coin.name}}</td>
  </tr> 
</table>

Finally, you can see in the browser: http://localhost:4200

You can see the data is displaying the table format.

In a real-world scenario, data is fetching from the Backend API. In this case, we have taken a simple static Array.

Global service vs Local Service Injection in Angular

To inject the service, you have two options.

#Inject as ‘global service’

To inject as global service, inject the service into the root module.

You need to register the module inside the app.module.ts file like we have done earlier in this post.

import { CryptoService } from './crypto.service'; 

@NgModule({ providers: [CryptoService], })

2) Inject as ‘local service’

To inject as local service, inject the service into component directly.

See the following code inside the app.component.ts file.

import { Component } from '@angular/core';
import { CryptoService } from './service/crypto.service';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [CryptoService]
})
export class AppComponent {
  title = 'app';
 
  constructor(calc:CalcService){
    //Use calc
  }
}

 So, we can register the service in Angular either locally or globally.

If you are using services on more than one component then you should define one global and otherwise local works just fine. It depends on the size of the project.

Finally, our Angular Services Tutorial With Example From Scratch is over.

Related Posts

Angular CRUD Example

Angular HttpClient Example

Angular File Upload Example

3 Comments
  1. Manish Sohaney says

    Indeed you explained Services concept in a very simple and straight forward way. Kudos to you!

    1. pani says

      i am getting the following error.

      TypeError: cryptoservice.getMyItems is not a function
      at new AppComponent (app.component.ts:16)

      please clarify me where am i do wrong?

      1. Aaag says

        // items.service.ts

        import { Injectable } from ‘@angular/core’;

        @Injectable()
        export class CryptoService {

        coins= [
        {id: 1, name: ‘BTC’},
        {id: 2, name: ‘XRP’}
        ];

        constructor() { }

        getMyItems()
        {
        return this.coins;
        }

        }

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.