How do we create service in Angular

How do we create service in Angular, Read More!!!

Step 1: – Create Service in your angular application

ng g s StateInformation

Step 2:- Here down below you can see the code which will generated.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class StateInformationService {

  constructor() { }
}

From Injectable, remove providedIn: ‘root’.

import { Injectable } from '@angular/core';

@Injectable()
export class StateInformationService {

  constructor() { }
}

Step 3: – Create Service class with dummy record, as shown in down below.

import { Injectable } from '@angular/core';

@Injectable()
export class StateInformationService {

  getStateNameSummary(): any[] {
    var StateNameSummary = [
      {
        Region: 'Gujarat',
        StateCode: 1,
        
      },
      { 
        Region: 'Rajasthan',
        StateCode: 2,
        
      },
      {
        Region: 'Punjab',
        StateCode: 3,
        
      },
      {
        Region: 'Haryana',
        StateCode: 4,        
      },
    ];
    return StateNameSummary;
  }
}

Step 4: – Create new module named AdminModule

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { StateWithServiceComponent } from './state-with-service/state-with-service.component';
import { StateInformationService } from '../state-information.service';

@NgModule({
  declarations: [
    
    StateWithServiceComponent,
  ],
  imports: [CommonModule, FormsModule],
  exports: [   
  ],
  providers: [StateInformationService],
})
export class AdminModule {}

Step 5:- Open StateInformation Component and write code in constructor.

constructor(private stateInfo:StateInformationService) { }
import { Component, OnInit } from '@angular/core';
import { StateInformationService } from 'src/app/state-information.service';

@Component({
  selector: 'app-state-with-service',
  templateUrl: './state-with-service.component.html',
  styleUrls: ['./state-with-service.component.scss']
})
export class StateWithServiceComponent implements OnInit {
  StateListSummary: any = [];
  constructor(private stateInfo:StateInformationService) { }

  ngOnInit(): void {
    this.StateListSummary = this.stateInfo.getStateNameSummary();
  }
}

Step 6: – Open State With Service Component. html File

<div class="col-12">
    <table class="table">
      <tr>
        <th>State Name</th>
        <th>State Code</th>
       
      </tr>
      <tr *ngFor="let StateSumary of StateListSummary">
        <td>
          <b>{{ StateSumary.Region }}</b>
        </td>
        <td>
          {{ StateSumary.StateCode }}
        </td>
       
      </tr>
    </table>
  </div>

Leave a Comment