ng generate interface employee
Tartalma:
export interface Employee { id: number; name: string; city: string; salary: number; }
//... import { HttpClientModule } from '@angular/common/http'; export const appConfig: ApplicationConfig = { providers: [ provideRouter(routes), importProvidersFrom(HttpClientModule) ] };
ng generate service shared/api
Importáljuk az app.component.ts fájlban:
import { Observable } from 'rxjs'; import { Employee } from '../employee';
Az ApiService osztály
export class ApiService { host = 'http://localhost:3000/' constructor(private http: HttpClient ) { } getEmployees(): Observable<Employee[]> { let endpoint = 'employees'; let url = this.host + endpoint; return this.http.get<Employee[]>(url); } }
ng generate component empl
Vegyük fel az empl komponenst az app komponensben:
<h1>Dolgozók</h1> <app-empl></app-empl>
Szerkesszük az src/app/empl/empl.component.ts fájlt.
Vegyük fel a következő import sorokat:
import { Employee } from '../employee'; import { ApiService } from '../shared/api.service';
Készítsünk egy adattagot employees néven, Employee[] típussal:
employees!: Employee[];
Injektáljuk az ApiService osztályt az EmplComponent osztályba.
constructor(private api: ApiService) { }
Készítsünk egy setEmployees() metódust:
setEmployees() { this.api.getEmployees().subscribe(result => { console.log(JSON.stringify(result)); this.employees = result; }) }
Hívjuk meg a metódust:
ngOnInit(): void { this.setEmployees() }
Szerkesszük az src/app/empl/empl.component.html sablonfájlt.
<table> <tr *ngFor="let employee of employees"> <td>{{employee.name}}</td> <td>{{employee.city}}</td> <td>{{employee.salary}}</td> </tr> </table>
export interface Employee { id: number; name: string; city: string; salary: number; }
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Employee } from '../employee'; @Injectable({ providedIn: 'root' }) export class ApiService { host = 'http://localhost:3000/' constructor(private http: HttpClient ) { } getEmployees(): Observable<Employee[]> { let endpoint = 'employees'; let url = this.host + endpoint; return this.http.get<Employee[]>(url); } }
import { Component, OnInit } from '@angular/core'; import { Employee } from '../employee'; import { ApiService } from '../shared/api.service'; @Component({ selector: 'app-empl', templateUrl: './empl.component.html', styleUrls: ['./empl.component.css'] }) export class EmplComponent implements OnInit { employees!: Employee[]; constructor(private api: ApiService) { } ngOnInit(): void { this.setEmployees() } setEmployees() { this.api.getEmployees().subscribe(result => { console.log(JSON.stringify(result)) this.employees = result; }) } }