Angular Service Example: How to Use Angular 12 Service

Services are not the Angular construct but rather a pattern. Angular Services are nothing more than a class to encapsulate some logic that you want to share across places in your application.  The Components should not get or store data directly, and they indeed shouldn’t knowingly present fake data.

Their main focus should be representing the data and delegate the data access to a service.

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

  1. Angular Router

  2. Angular Form Validation

  3. Angular Dependency Injection

What is Angular Service

Angular Service is typically a class with a well-defined purpose. It should do specific and do it well. Thus, angular distinguishes components from services.

Services in Angular are a great deal to share information among classes that do not know each other.  When we develop the Angular app, we will most likely run into an outline in which we need to use the same code across multiple angular components. In that case, the Services will help us to get rid of that problem.

We can share the services code among various angular components.

With Angular’s dependency injectionyou can inject the services around your app. To create the service class, you do not need to do anything Angular-specific. 

There is no metadata needed. There is not some naming convention needed or some functional interface that is required to be implemented. They are just plain classes that you will create to modularize the reusable code.

Why do we use Angular Service?

There are many reasons why you would want to create and use the services in your Angular applications. One of the most common is the data service. The class that will handle getting and setting data from your data store.

The data service that gets injected into each of those components allows you not to recreate the same datastore connection code in each component. Another common use of service is for some business logic.

The Angular framework has classes that are necessarily service classes. Things like Http, FormBuilder, and more, contain logic for doing specific things that are non-component specific. And again, through the dependency injection engine, you can get these services sent into your class constructors and use them.

Services in Angular provide an architectural way to encapsulate business logic in a reusable fashion, allowing you to keep that logic out of your components, directives, and pipe classes. This is beneficial for modularity and single responsibility type of simplicity tier code, but it also makes the code more testable. 

If you employ a unit testing strategy, it becomes straightforward to mock the services that get used in a component. Thus your unit test can focus purely on confirming the behavior of the component and not its dependencies. 

The same goes for your services that get other services provided to them. So services, while not an enforced construct, are a fundamental building block to an Angular application.

We should not violate general programming principles like Single Responsibility of Class.

In this case, Components use to display and present the data. Services use to fetch data from an API. Let’s start with our Angular Service Example.

Step 1: Install Angular via CLI.

You need to set up the 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 folder 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 the following two options.

#Inject as ‘global service.’

To inject as a global service, inject a 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. But, again, it depends on the size of the project.

Finally, our Angular Service Example Tutorial is over.

Related Posts

Angular CRUD

Angular HttpClient

Angular File Upload

3 thoughts on “Angular Service Example: How to Use Angular 12 Service”

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

      Reply
      • // 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;
        }

        }

        Reply

Leave a Comment

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