How to create Service in Angular

1. service file name is data.ts

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

@Injectable({
  providedIn: 'root',
})
export class DataService {
  info1: string[] = ['john Methew', 'ES23', 'john@agmail.net'];

  info2: string[] = ['Robo wilson', 'ES22', 'RoboWilson@agmail.net'];

  info3: string[] = ['rose adams', 'ES25', 'roseadams@agmail.net'];

  getInfo1(): string[] {
    return this.info1;
  }

  getinfo2(): string[] {
    return this.info2;
  }

  getinfo3(): string[] {
    return this.info3;
  }


  addInfo(info:string){
    this.info1.push(info);
    this.info2.push(info);
    this.info3.push(info);
    return this.info1
  }
  constructor() {}
}


2. Now this file is component of e-info.ts



import { Component } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-e-info',
  templateUrl: './e-info.component.html',
  styleUrls: ['./e-info.component.css'],
  providers:[DataService]  
})
export class EInfoComponent {

  infoReceived1:string[]=[];
  infoReceived2:string []=[];
  infoReceived3:string []=[];
 

  getInfoFromService1(){
    return this.infoReceived1=this.dservice.getInfo1();
  }

  getInfoFromService2(){

    return this.infoReceived2=this.dservice.getinfo2();

  }

  getInfoFromService3(){

    return this.infoReceived3=this.dservice.getinfo3();

  }

  constructor(private dservice:DataService){

  }
  ngOnInit(): void {
    //Called after the constructor, initializing input properties, and the first call to ngOnChanges.
    //Add 'implements OnInit' to the class.
   
  }

  updateInfo(frm:any){
    this.dservice.addInfo( frm.value.location);
  }

}


3. this file is html page e-info.html 


<form #frm="ngForm" (ngSubmit)="updateInfo(frm )">
    <div class="">
        <input type="text" name="location" value="" ngModel/>
        <button type="button" name="button">Add Info</button>
    </div>
</form>

<button type="button" class="button" (click)="getInfoFromService1()">Employee1</button>                      
<ul>
    <li *ngFor="let info of infoReceived1">{{info}}</li>
</ul>

<button type="button" class="button" (click)="getInfoFromService2()">Employee2</button>                      
<ul>
    <li *ngFor="let info of infoReceived2">{{info}}</li>
</ul>

<button type="button" class="button" (click)="getInfoFromService3()">Employee3</button>                      
<ul>
    <li *ngFor="let info of infoReceived3">{{info}}</li>
</ul>


4. And finally output is 



Post a Comment

0 Comments