Home > Back-end >  Angular: Object has values, but properties are undefined
Angular: Object has values, but properties are undefined

Time:10-19

so I'm getting data from my rest service the Dto is filled, but when I try to get to the properties it is undefined.

Here I'm getting the Data

this.mapservice.getAllCoordinates().subscribe((data: CoordinateDto[]) => {
  this.coordinates = data;
  this.parseMapCoordinates();
  this.initLocation();
});

Here I try to parse it to a number, so I can fill my other Object with it. But the Properties are all undefined.

  parseMapCoordinates() {
   let newCoords: MapCoordinates;
   this.coordinates.forEach((coords) => {
     console.log(coords);
     console.log(coords.user_Id);
     console.log(coords.date);
     console.log(coords.koordinate);
     newCoords.latitude = parseFloat(coords.koordinate.split(', ')[0]);
     newCoords.longitude = parseFloat(coords.koordinate.split(', ')[1]);
     this.mapCoordinates.push(newCoords);
   });
  }

When I hover over coords it shows me the values, but when i hover over koordinate it says 'undefined' and I don't know why.

And this is the log

And last the Dto

export interface CoordinateDto{
koordinate: string;
date: Date;
user_Id: number;

Thank you for your help :)

CodePudding user response:

this.coordinates is an array of items. so you need to access it with its index, for eg:

 parseMapCoordinates() {
   let newCoords: MapCoordinates;
   for (let i = 0; i < this.coordinates.length; i  ) {
     const coords = this.coordinates[i];
     console.log(coords);
     console.log(coords.user_Id);
     console.log(coords.date);
     console.log(coords.koordinate);
     newCoords.latitude = parseFloat(coords.koordinate.split(', ')[0]);
     newCoords.longitude = parseFloat(coords.koordinate.split(', ')[1]);
     this.mapCoordinates.push(newCoords);
   }

  }

CodePudding user response:

Change the interface to class. The interface does not have initial data, it mostly defines only types:

export interface CoordinateDto{
    koordinate: string;
    date: Date;
    user_Id: number;
}

to

export class CoordinateDto {
        koordinate: string;
        date: Date;
        user_Id: number;

        constructor() {
            this.koordinate = '';
            this.date = new Date();
            this.user_Id = 0;
        }
}

and after that, in your parseMapCoordinates() function

instead of let newCoords: MapCoordinates; change to let newCoords = new CoordinateDto();

  • Related