首页 > 解决方案 > Angular:对象具有值,但属性未定义

问题描述

所以我从我的休息服务中获取数据,Dto 已填充,但是当我尝试获取属性时,它是未定义的。

我在这里获取数据

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

在这里,我尝试将其解析为一个数字,这样我就可以用它填充我的另一个对象。但是属性都是未定义的。

  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);
   });
  }

当我将鼠标悬停在坐标上时,它会显示值,但是当我将鼠标悬停在坐标上时,它会显示“未定义”,我不知道为什么。

这是日志

最后是 Dto

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

谢谢您的帮助 :)

标签: angular

解决方案


this.coordinates是一个项目数组。所以你需要使用它的索引来访问它,例如:

 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);
   }

  }

推荐阅读