How To Create Services In Angular Using Model

In this article, we will learn what services are and how to create services into Angular using Model.

Introduction

 
In this article, we will learn what services are and how to create services into Angular using Model.
 
We have already seen how to create your first Angular application in my previous article i.e. Getting started with Angular
 
Also, we have discussed How to create components in Angular
 
As there are always new Angular versions, do not worry as new versions include some new features.
 
We are not going to cover these in this article, will cover these later.
 

What Are Services in Angular

  • Angular services are singleton objects which get instantiated when necessary.
  • The primary usage of service is to share business logic, models, or data and functions with different components of an Angular application.
  • Service can be created by using command line as ng g service our_service_name.

Why Services in Angular?

  • Code separation is the main objective of service.
  • These play an important role to invoke the function from controller, directives, etc.
  • Share the business logic through the application.
  • Easily inject the service.
Step 1
 
To create services, go to src/app as you can see from the folder structure. Now, create a Service folder. After that open this folder. See the below image & type cmd then press Enter key, so the command prompt will open.
 
  
 
To create different services, use the following syntax.
  1. ng g service our_service_name  
Will create product service as shown below using the above syntax.
 
 
 
It will create a service & automatically reference gets added into a app.module.ts file. For more information see below code of app.module.ts
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3.   
  4. import { AppRoutingModule } from './app-routing.module';  
  5. import { RouterModule } from '@angular/router';   
  6. import { AppComponent } from './app.component';  
  7. import { HomeComponent } from './components/home/home.component';  
  8. import { AboutusComponent } from './components/aboutus/aboutus.component';  
  9. import { ContactusComponent } from './components/contactus/contactus.component';  
  10. import { ProductsComponent } from './components/products/products.component';  
  11. import { ProductService } from './Service/product.service';  
  12.   
  13. @NgModule({  
  14.   declarations: [  
  15.     AppComponent,  
  16.     HomeComponent,  
  17.     AboutusComponent,  
  18.     ContactusComponent,  
  19.     ProductsComponent  
  20.   ],  
  21.   imports: [  
  22.     BrowserModule,  
  23.     AppRoutingModule,  
  24.     RouterModule.forRoot([    
  25.       { path: 'about', component: AboutusComponent },  
  26.       { path: 'contact', component: ContactusComponent },  
  27.       { path: 'products', component: ProductsComponent }  
  28.      ]),  
  29.   ],  
  30.   providers: [ProductService],  
  31.   bootstrap: [AppComponent]  
  32. })  
  33. export class AppModule { }  
Step 2
 
Now we will create one model folder in which we will create one model of Product which contains some properties.
 
Create a Model folder into a app folder. Now open the command prompt & create a class using the below syntax
  1. ng g class Product    
Step 3
 
Open our project into a Visual Studio Code & add the below properties into above class i.e Product.ts
 
Here .ts means TypeScript file. In TypeScript, variable declaration has a syntax like Variable_Name: Data_Type = [Optional_Value]
  1. export class Product {  
  2.     productId: number;  
  3.     productName: string;  
  4.     productPrice: number;  
  5.     productDesc: string;  
  6. }  
Step 4
 
Now go to services folder & open file product.service.ts 
 
Write the below code into the above file, I have imported a above Product Model from step 3. Will create an object & assign some dummy data values into it using Array.
 
Note: Here as per your need you can consume the WebApi services. For demo purposes I have used hard code data. 
  1. import { Injectable } from '@angular/core';  
  2. import { Product } from '../model/product' ;  
  3.   
  4.   
  5. @Injectable({  
  6.   providedIn: 'root'  
  7. })  
  8. export class ProductService {  
  9.   productList: Array<Product> = ([  
  10.     { productId: 1, productName: 'Mobile', productPrice: 12000, productDesc: 'New Mobile' },  
  11.     { productId: 2, productName: 'Computer', productPrice: 30000, productDesc: 'New Computer' },  
  12.     { productId: 3, productName: 'Cabinet', productPrice: 800, productDesc: 'New Cabinet' },  
  13.     { productId: 4, productName: 'HDD', productPrice: 1000, productDesc: 'New HDD' }  
  14.   
  15.   ])  
  16.   constructor() { }  
  17.   get() {  
  18.     return this.productList;  
  19.   }  
  20. }  
Step 5
 
Create component products, so open component folder & open it into a terminal or command prompt & create a component using syntax 
  1. ng g c products  
Write the below code into file products.component.ts. Here I am importing ProductService & calling a get method to get data into a productList which is of type any. In typeScript there is a data type any so we can assign values of any data type to it. 
  1. import { Component, OnInit } from '@angular/core';  
  2. import { ProductService } from '../../Service/product.service';  
  3. import { BrowserModule, Title } from '@angular/platform-browser';  
  4.   
  5. @Component({  
  6.   selector: 'app-products',  
  7.   templateUrl: './products.component.html',  
  8.   styleUrls: ['./products.component.css']  
  9. })  
  10. export class ProductsComponent implements OnInit {  
  11.   
  12.   productList: any;    
  13.   constructor(private productService: ProductService, private title: Title) { }  
  14.   
  15.   ngOnInit() {  
  16.     this.title.setTitle("Product List");  
  17.     this.productList = this.productService.get();  
  18.   }  
  19. }  
Step 6: Now open product.component.html & write the below code into it. Here I am using ngFor to bind the data values from our variable using a loop. Here in the loop I am using our Model.
 
products.component.html 
  1. <p>  
  2.   products works!  
  3. </p>  
  4.   
  5. <table class="gridList">  
  6.   <tr>  
  7.     <th>Product Id</th>  
  8.     <th>Product Name</th>  
  9.     <th>Product Price</th>  
  10.     <th>Description</th>  
  11.   </tr>  
  12.   <tr *ngFor="let item of productList">  
  13.     <td>{{item.productId}}</td>  
  14.     <td>{{item.productName }}</td>  
  15.     <td>{{item.productPrice}}</td>  
  16.     <td>{{item.productDesc}}</td>  
  17.   </tr>  
  18. </table>  
Step 7: Run our project using command line or terminal 
  1. ng g serve -o  
Click on "Products" button and it will redirect you to the Products component, you will get output like below
 
 
 

Summary

 
In this article, you learned how to create services in Angular using Model.