angular - Typescript: Konvertera json från api-anrop till Array<object>
Från API får jag detta JSON:
[{
"id: "0",
"name_surname": "John Smith",
"age": 33,
"profile__image": "..."
},{
"id: "1",
"name_surname": "Juan García",
"age": 32,
"profile__image": "..."
}]
Jag har nästa klass i TypeScript:
export class Employee {
public Id: string = null;
public NameSurname: string = null;
public Age: number = 0;
public ProfileImage: string = null;
}
Jag vill returnera resultatet av API-anropet som Array<Employee>.
Som du ser i API-anropet får jag arrayen med egenskaperna separerade med understreck (_). Hur kan jag konvertera till standardklass utan understreck?
Svar #1
Demo lägg till konstruktor till din Employee-modell
export class Employee {
public Id: string = null;
public NameSurname: string = null;
public Age: number = 0;
public ProfileImage: string = null;
constructor(param:any){
this.Id=param.id;
this.NameSurname=param.name_surname,
this.Age=param.age,
this.ProfileImage=param.profile__image
}
}
då i komponentkarta dataresultat till din modell
result:Employee[];
this.result=this.data.map(x=> new Employee(x));
Demo2 om du inte vill använda konstruktorn så kan du definiera en funktion inuti din modell.
export class Employee {
public Id: string = null;
public NameSurname: string = null;
public Age: number = 0;
public ProfileImage: string = null;
constructor(){ }
mapObj(param:any){
this.Id=param.id;
this.NameSurname=param.name_surname,
this.Age=param.age,
this.ProfileImage=param.profile__image
return this;
}
}
då kan du ringa som
this.result=this.data.map(x=> new Employee().mapObj(x));
Svar #2
Skapa en funktion för att konvertera datan
import {CommonModule} from '@angular/common';
import {Component, } from '@angular/core';
import {bootstrapApplication} from '@angular/platform-browser';
export class Employee {
public Id: string = '';
public NameSurname: string = '';
public Age: number = 0;
public ProfileImage: string = '';
}
const data = [{
"id": "0",
"name_surname": "John Smith",
"age": 33,
"profile__image": "..."
},{
"id": "1",
"name_surname": "Juan García",
"age": 32,
"profile__image": "..."
}]
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
templateUrl: `<div>{{employee | json}}</div>`,
})
export class AppComponent {
employee: Employee[] = []
constructor() {
this.employee = this.dataToEmployee()
}
dataToEmployee = (): Employee[] =>
data.map((x) => ({
Id: x.id,
NameSurname: x.name_surname,
Age: x.age,
ProfileImage: x.profile__image,
}))
}
bootstrapApplication(AppComponent);
