In order to retrieve the JSON response of a GET request made by a service within my app to our backend, extract specific parts from it, and store them in an Array based on an Interface I have created for future use.
Here is a sample of the JSON data:
[{
"id": 1,
"name": "Lar das meninas",
"latitude": -23.6695527,
"longitude": -46.603418,
"about": "About the orphanage",
"instructions": "Come visit us",
"opening_hours": "From 8am to 6pm",
"open_on_weekends": false,
"directory": {
"directoryName": "/PROD/FILE",
"server": {
"serverName": "XYZ34"
}
}
},
{
"id": 2,
"name": "Petito Orphanage",
"latitude": -23.6740118,
"longitude": -46.6066612,
"about": "About the orphanage",
"instructions": "Come visit us",
"opening_hours": "From 8am to 6pm",
"open_on_weekends": false,
"directory": {
"directoryName": "/PROD/FILE",
"server": {
"serverName": "XYZ34"
}
}
}
]
I am interested in extracting the fields name, latitude, longitude, directoryName, and serverName from this data. To achieve this, I defined an interface as follows:
export interface Orphanage {
name: string,
latitude: number,
longitude: number
}
My initial attempt was to utilize TypeScript's matching mechanism to map these fields, calling the HTTP endpoint using the provided service, but the console output displayed the entire response instead of the required fields.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { Orphanage } from './orphanage';
import { tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class OrphanageService {
constructor(private http: HttpClient) { }
getOrphanages() {
return this.http.get<Orphanage[]>('http://localhost:3333/orphanages').pipe(
tap((res: Orphanage[]) => console.log(res))
);
}
}
I attempted another approach by subscribing to the Observable returned by the service within the component, assigning the extracted data to a property, and logging it, yielding the same undesired outcome.
import { Component, OnInit } from '@angular/core';
import { Orphanage } from '../orphanage';
import { OrphanageService } from '../orphanage.service';
@Component({
selector: 'app-orphanages-main',
templateUrl: './orphanages-main.component.html',
styleUrls: ['./orphanages-main.component.scss']
})
export class OrphanagesMainComponent implements OnInit {
orphanages: Orphanage[];
constructor(private orphanageService: OrphanageService) { }
ngOnInit(): void {
this.orphanageService.getOrphanages()
.subscribe((orphanages: Orphanage[]) => {
this.orphanages = orphanages;
console.log(this.orphanages);
});
}
}
To effectively filter out only the necessary fields and address the nested structure including directoryName and serverName, further steps and adjustments need to be undertaken.
I appreciate any guidance or insights on how to proceed in achieving this goal.
Thank you!