I am working on the Clinic Manager project using the MEAN stack. I have already dealt with the backend, and now I want to display data using Angular. However, I am facing a problem with retrieving data and assigning it to a TypeScript object. I have been trying to solve this problem for a couple of hours, and ChatGPT hasn't been helpful at all. I'm stuck.
I am receiving data from the server in JSON format, and it looks like this:
{
"status": "success",
"data": {
"count": 9,
"patients": [
{
"_id": "64787ffc3daccbe20796ec17",
"name": "Paweł",
"surname": "Kowalczyk",
"dateOfBirth": "1990-09-09T22:00:00.000Z",
"city": "Warszawa",
"pesel": "10207935608",
"address": "Marszałkowska 155"
},
{
"_id": "64787ffc3daccbe20796ec1a",
"name": "Alicja",
"surname": "Krawczyk",
"dateOfBirth": "1988-09-15T00:00:00.000Z",
"city": "Poznań",
"pesel": "70810738509",
"address": "Krakowska 45"
},
data.service.ts
export class DataService {
constructor(private http: HttpClient) { }
getData(): Observable<any> {
return this.http.get<any>('http://localhost:7000/api/v1/patients')
}
}
patient.model.ts
export class Patient {
id: string
name: string
surname: string
pesel: string
dateOfBirth: Date
city: string
address: string
constructor(
_id: string,
name: string,
surname: string,
dateOfBirth: Date,
pesel: string,
city: string,
address: string) {
this.id = _id
this.name = name
this.surname = surname
this.pesel = pesel
this.dateOfBirth = dateOfBirth
this.city = city
this.address = address
}
// getName() {
// return this.name
// }
}
And here is my problem, I don't know how to cast my response to patient.model. I assume that creating object by hand is not the answer.
patients.component.ts
export class PatientsComponent implements OnInit {
patients: Patient[] = []
isLoading = true
constructor(private dataService: DataService) { }
ngOnInit(): void {
this.dataService.getData().subscribe((data) => {
this.patients = data.data.patients.map((patientData: any) => new Patient(patientData))
})
}
}
I've tried something like these:
patients.component.ts
export class PatientsComponent implements OnInit {
patients: Patient[] = []
isLoading = true
constructor(private dataService: DataService) { }
ngOnInit(): void {
this.dataService.getData().subscribe((data) => {
this.patients = data.data.patients as Patient[]
})
}
}
and
this.dataService.getData().subscribe((data) => {
this.patients = <Patient[]>data.data.patients
})
or
ngOnInit(): void {
this.dataService.getData().subscribe((data) => {
this.patients = data.data.patients.map((patientData: any) => new Patient(patientData))
})
}
But it gives me an error or it simply doesn't work (I don't get an array of Patient, just an array of objects). What am I doing wrong?