Introduction To Angular Services

Introduction To Angular Services

In this article, we will learn how to make a simple component that gets a list of items from an Angular Service and shows it in our template. A Service is a type of class that provides a service to a component, directive, or another service. The Service could be retrieving data from the back end, executing business logic, and so on.

What is Angular Service

A service is a reusable piece of code with a specific purpose. You will use this code in a lot of different parts of your program.

Our components require data access. You can put data access code in each component, but this is wasteful and violates the single-responsibility principle. The focus of the Component should be on displaying data to the user. Data collection from the back-end server must be assigned to another class. A class like this is known as a Service class. Because it serves as a data provider for all components that require it.

What Angular Services are used for

  • Logging services, for example, are features that are not dependent on other components.
  • Logic or data can be shared between components.
  • External interactions, such as data access, should be encapsulated.

Advantageous of Angular Service

  • It is simpler to test services.
  • They are less difficult to debug.
  • We can use the service in a variety of settings.

How to create a Service in Angular

A Javascript function is all that an Angular service is. All we have to do now is construct a class and populate it with methods and properties. We can then call the methods of this class by creating an instance of it in our component.

Getting data from a data source is one of the best uses of services. Let's construct a basic service that retrieves product information and sends it to our component.

Product Model

Create a new file called product.ts in the src/app folder.

export class Product { 
 
    constructor(productID:number,    name: string ,   price:number) {
        this.productID=productID;
        this.name=name;
        this.price=price;
    }
 
    productID:number ;
    name: string ;
    price:number;
 
}

Our domain model is the Product class.

Product Angular Service

Let's now create an Angular Service that returns a list of products.

Make a new file called product.service.ts in the src/app folder.
import {Product} from './product'
 
export class ProductService{
 
    public  getProducts() {
 
        let products:Product[];
 
        products=[
            new Product(1,'Memory Card',500),
            new Product(1,'Pen Drive',750),
            new Product(1,'Power Bank',100)
        ]
 
        return products;               
    }
}

First, we import the Product from the Product.ts 

Then, create and export the ProductService class. We must export it in order for the Components & Other service class to import and use it.

The getProducts function returns the product collection. We've hardcoded the products in this example. To obtain the data in real life, you'd use an HTTP GET request to your back end API.

Our service is now available.

It's worth noting that the aforementioned class is merely a JavaScript function. It has nothing to do with Angular.

Invoking the ProductService

The component's next action is to call the ProductService. Add the following code to the app.componet.ts file.
import { Component } from '@angular/core';
 
import { ProductService } from './product.service';
import { Product } from './product';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
 
export class AppComponent
{
 
   products:Product[];
   productService;
 
   constructor(){
     this.productService=new ProductService();
   }
 
   getProducts() {
     
     this.products=this.productService.getProducts();
   }
  
}

We begin by importing the Product and ProductService categories.

In the function constructor of the AppComponet, we build a ProductSerivce instance. We use Angular's Dependency Injection to inject the ProductSerivce in the constuctor in real-world Angular Apps. That will be covered in the future article.

The ProductService's getProducts method is called by the getProducts method of the getProducts method. It gives us a list of Products, which we save in the products local variable.

Template

The following step is to show the products to the user.

Add the following code to the app.component.html file.
<div class="container">
    <h1 class="heading"><strong>Services </strong>Demo</h1>
 
    <button type="button" (click)="getProducts()">Get Products</button>
 
     <div class='table-responsive'>
            <table class='table'>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Price</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let product of products;">
                        <td>{{product.productID}}</td>
                        <td>{{product.name}}</td>
                        <td>{{product.price}}</td>
                    </tr>
                </tbody>
            </table>
        </div>
 
</div>

Our template is styled with the Bootstrap 4 framework. The link can be found in the index.html file.

The Get Products button uses event binding to call the component class's getProducts function.

We use the ngFor directive to loop through the products and display them in a table.

You may now run the application and select the Get Product option. The Products List will appear.


Example of Angular Services

Injecting Services into Component

We directly instantiated the productService in the Component in the example, as shown below.

this.productService=new ProductService();

The disadvantages of directly instantiating the service, as indicated above, are numerous.

The Component and the ProductService are inextricably linked. If the ProductService class definition is changed, all code that uses the service must be updated.

If we wish to replace ProductService with BetterProductService, we must manually search for and replace ProductService anywhere it is used.

Testing becomes more challenging. It's possible that we'll need to supply a mockProductService for testing and a ProductService for production.

This can be solved with Angular Dependency Injection, which will be covered in our future article.

Conclusion

In this article, We covered how to make a simple component that gets a list of items from an Angular Service and shows it in our template.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post