In this Angular Services tutorial, we will show you how to build a simple component that fetches a
Our components need to access to data. You can write data access code in each component, but that is very inefficient and breaks the rule of single responsibility. The Component must focus on presenting data to the user. The task of getting data from the back end server must be delegated to some other class. Such a class is called service class. Because it provides the service of providing data to every component that needs it.
Applies to: Angular 2 to the latest edition of i.e. Angular 8. Angular 9, Angular 10, Angular 11
Table of Content
What is a Service
Service is a piece of reusable code with a focused purpose. A code that you will use it in many components across your application
What services are used for
- Features that are independent of components such a logging services
- Share logic or data across components
- Encapsulate external interactions like data access
Advantageous of Service
- Services are easier to test.
- Services are easier to Debug.
- You can reuse the service.
How to create a Service in Angular
An Angular service is simply a Javascript function. All we need to do is to create a class and add methods & properties. We can then create an instance of this class in our component and call its methods.
One of the best uses of services is to get the data from the data source. Let us create a simple service, which gets the product data and passes it to our component.
You can download the source code from gitHub.
Best Angular Books
The Top 8 Best Angular Books, which helps you to get started with Angular
Product
Create a new file under the folder src/app
and call it product.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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; } |
The Product
class above is our domain model.
Product Service
Next, let us build an Angular Service, which returns the list of products
.
Create a new file under the folder src/app
and call it product.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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 have imported the Product
We have created the ProductService
class and exported it.
We have created a getProducts
method, which returns the collection of the products
. In this example, we have hard coded the products
. In real life, you would send an HTTP request to your back end API to get the data
Now our service is ready.
Note that the above class is a simple JavaScript function. There is nothing Angular about it.
Invoking the ProductService
The Next step is to invoke the ProductService
from the component. Open the app.componet.ts
and add the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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(); } } |
First, we have imported both Product
& ProductService
In the constructor of the AppComponet
, we have created the instance of the ProductSerivce
The getProducts
method calls the getProducts
method of the ProductService.
The returned list of Products are stored in the local variable products
Template
The next step is to display the Products
to user
Open the app.component.html
file and add the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <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> |
We are using the bootstrap 3
to style our template here
We have added a button “Get Products”, which is hooked to getProducts
method of the component class via event binding
We are displaying the returned products via ngFor directive.
Finally, run the code and click on the Get Product button and see the Products are displayed.
Injecting Services into Component
In the example, we instantiated the productService
in the Component directly as shown below
1 2 3 | this.productService=new ProductService(); |
Directly instantiating the service, as shown above, has many disadvantageous
- The
ProductService
is tightly coupled to the Component. If we change theProductService
class definition, then we need to update every code where service is used - If we want to change
ProductService
withBetterProductService
, then we need to search wherever theProductService
is used and manually change it - Makes Testing difficult. We may need to provide
mockProductService
for testing and use theProductService
for Production.
This problem can be solved by Angular Dependency injection. You can learn it from our next tutorial on Dependency Injection in Angular 2.
Suggested Reading
Angular Dependency Injection
Angular Injector
Angular Providers
Angular Hierarchical Dependency Injection