Hi there, I am facing a challenge while trying to convert an array of JSON objects into a TypeScript class. Every time I try to assign a JSON object attribute to a TypeScript attribute, the method crashes.
Here is the TypeScript interface I am working with:
export interface marker {
lat: number;
lng: number;
}
Below is the TypeScript method in question:
public markers: marker[];
ngOnInit() {
this.mapService.GetPhotosById(this.id).subscribe(resultlisting => {
this.values = resultlisting;
console.log(this.values);
this.ChangetoMarkers(this.values);
}, error => this.errorMessage = error);
}
ChangetoMarkers(someArray: Observable<any[]>) {
for (let entry of someArray) {
let mark: marker;
mark.lat = Number(entry.latitude);
mark.lng = +entry.longitude;
this.markers.push(mark);
};
console.log(this.markers);
}
Next up, the Map Service implementation:
GetPhotosById(id: string): Observable<any> {
return this.http
.post(this.config.apiEndpoint + "mapPhotos/" + id)
.map(this.extractJson).catch(this.handleErrors);
};
private extractJson(res: Response) {
let data = res.json();
return data;
}
private handleErrors(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.log(errMsg);
return Observable.throw(errMsg);
}
I have tried applying integer casting but it hasn't resolved the issue. Any help or suggestions would be highly appreciated.