Introduction
In this article, we will learn what services are and how to create services into Angular using Model.
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.
- 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
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
-
- import { AppRoutingModule } from './app-routing.module';
- import { RouterModule } from '@angular/router';
- import { AppComponent } from './app.component';
- import { HomeComponent } from './components/home/home.component';
- import { AboutusComponent } from './components/aboutus/aboutus.component';
- import { ContactusComponent } from './components/contactus/contactus.component';
- import { ProductsComponent } from './components/products/products.component';
- import { ProductService } from './Service/product.service';
-
- @NgModule({
- declarations: [
- AppComponent,
- HomeComponent,
- AboutusComponent,
- ContactusComponent,
- ProductsComponent
- ],
- imports: [
- BrowserModule,
- AppRoutingModule,
- RouterModule.forRoot([
- { path: 'about', component: AboutusComponent },
- { path: 'contact', component: ContactusComponent },
- { path: 'products', component: ProductsComponent }
- ]),
- ],
- providers: [ProductService],
- bootstrap: [AppComponent]
- })
- 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
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]
- export class Product {
- productId: number;
- productName: string;
- productPrice: number;
- productDesc: string;
- }
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.
- import { Injectable } from '@angular/core';
- import { Product } from '../model/product' ;
-
-
- @Injectable({
- providedIn: 'root'
- })
- export class ProductService {
- productList: Array<Product> = ([
- { productId: 1, productName: 'Mobile', productPrice: 12000, productDesc: 'New Mobile' },
- { productId: 2, productName: 'Computer', productPrice: 30000, productDesc: 'New Computer' },
- { productId: 3, productName: 'Cabinet', productPrice: 800, productDesc: 'New Cabinet' },
- { productId: 4, productName: 'HDD', productPrice: 1000, productDesc: 'New HDD' }
-
- ])
- constructor() { }
- get() {
- return this.productList;
- }
- }
Step 5
Create component products, so open component folder & open it into a terminal or command prompt & create a component using syntax
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.
- import { Component, OnInit } from '@angular/core';
- import { ProductService } from '../../Service/product.service';
- import { BrowserModule, Title } from '@angular/platform-browser';
-
- @Component({
- selector: 'app-products',
- templateUrl: './products.component.html',
- styleUrls: ['./products.component.css']
- })
- export class ProductsComponent implements OnInit {
-
- productList: any;
- constructor(private productService: ProductService, private title: Title) { }
-
- ngOnInit() {
- this.title.setTitle("Product List");
- this.productList = this.productService.get();
- }
- }
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
- <p>
- products works!
- </p>
-
- <table class="gridList">
- <tr>
- <th>Product Id</th>
- <th>Product Name</th>
- <th>Product Price</th>
- <th>Description</th>
- </tr>
- <tr *ngFor="let item of productList">
- <td>{{item.productId}}</td>
- <td>{{item.productName }}</td>
- <td>{{item.productPrice}}</td>
- <td>{{item.productDesc}}</td>
- </tr>
- </table>
Step 7: Run our project using command line or terminal
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.