19 April 2020

Service example in angular


  • Open Command prompt and use below commands to create angular project
  • E:
  • cd E:\TestProjects\Angular
  • ng new service-example-in-angular --style=scss --routing --skip-install
  • cd service-example-in-angular
  • npm install
  • Open project in visual studio code.
  • Go to App folder then right click on app folder click on Generate Service like below image.

  • Then enter service name as below image. in my case "student" is module name.

  • Then click on enter. it will create student service (student.service.ts and other files) as below image.

  • Now create Student components in app folder.
  • Update student.service.ts file as below.

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

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

      getStudentsList(): any[]
      {
        var StudentsList = [
          {Id:101Name: "Adi"Email:"jc.adi101@gmail.com" },
          {Id:102Name: "Pavan"Email:"pavan@gmail.com"},
          {Id:103Name: "Nani"Email:"Nani@gmail.com" },
          {Id:104Name: "Madhan"Email:"Madhan@gmail.com" }
        ];
        return StudentsList;
      }
    }
  • Update student.component.ts file as below.

  • import { ComponentOnInit } from '@angular/core';
    import { StudentService } from '../student.service';


    @Component({
      selector: 'app-student',
      templateUrl: './student.component.html',
      styleUrls: ['./student.component.css']
    })
    export class StudentComponent implements OnInit {
      StudentsList = [];
      constructor(private studentServiceStudentService )
      {
      }
      ngOnInit() {
        this.StudentsList = this.studentService.getStudentsList();
      }
    }
  • Update student.component.html file as below.

  • <table>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Email</th>
      </tr>
      <tr *ngFor="let student of StudentsList">
        <td>
          {{student.Id}}
        </td>
        <td>
          {{student.Name}}
        </td>
        <td>
          {{student.Email}}
        </td>
      </tr>

    </table>
  • Update app.component.html file as below.

  • <h1>Service example in angular</h1>
    <app-student></app-student>

    Output:


    No comments:

    Post a Comment