Tartalomjegyzék

< Angular httpclient

Angular HttpClient - Összetett válaszok

Bevezetés

Ha REST API összetett választ ad, az adatokat le kell választanunk a meta adatokról.

REST API válasz

{
	"success": true,
	"data": [
		{
			"id": 1,
			"name": "Erős István",
			"city": "Szeged",
			"salary": null,
			"rankId": -1,
			"created_at": "2023-05-20T13:04:59.000000Z",
			"updated_at": "2023-05-20T13:04:59.000000Z"
		},
		{
			"id": 2,
			"name": "Tar Árpád",
			"city": "Szolnok",
			"salary": null,
			"rankId": -1,
			"created_at": "2023-05-20T13:05:34.000000Z",
			"updated_at": "2023-05-20T13:05:34.000000Z"
		}
	]
}

Interfészek

src/app/employee.ts
export interface Employee {
    id: number;
    name: string;
    city: string;
    salary: number;
    rankId: number;
}
src/app/response.ts
import { Employee } from "./employee";
 
export interface Response {
    success: boolean,
    data: Employee[]
}

Szolgáltatás

src/app/shared/empapi.service.ts
//...
import { map } from 'rxjs';
import { environment } from 'src/environments/environment';
 
//...
 
import { Response } from '../response';
 
  getEmployees() {
    let endpoint = 'employees';
    let url = environment.host + endpoint;
    return this.http.get<Response>(url).pipe(map(res => res.data));
  }