微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从 Angular 服务地图获取 NaN

如何解决从 Angular 服务地图获取 NaN

我正在使用一个 API,它可以从这样的哈利波特角色中返回数据

来自端点的数据

    "name": "Harry Potter","species": "human","gender": "male","dateOfBirth": "31-07-1980","yearOfBirth": 1980,"eyeColour": "green","hairColour": "black","wand": {
        "wood": "holly","core": "phoenix feather"
    },"patronus": "stag","hogwartsstudent": true,"hogwartsstaff": false,"actor": "Daniel Radcliffe","alive": true,"image": "http://hp-api.herokuapp.com/images/harry.jpg"
},

有了这些信息,我想显示一个字符列表,但只包含其中的几个属性:姓名、守护神、年龄和图像,我提出了下一个建议......

TypeScript 接口:

export interface Character {
    name: string;
    patronus: string;
    dateOfBirth: string;
    image: string;
    age: number;
}

服务我有一个

服务方式:

getStudents() {
return this.http.get<Character[]>(this.baseUrl + 'students').pipe(
  map( response => 
    response.map(
      respItem => (
        {
          name: respItem.name,patronus: respItem.patronus,dateOfBirth: respItem.dateOfBirth,image: respItem.image,age: new Date().getFullYear()  -  new Date(respItem.dateOfBirth).getFullYear() 
          
        }
        
      )
    ) 
  )

);

}

正如您在服务中看到的,我正在使用地图来获取年龄减去 DateOfBirth 的年份到今天日期的年份。 (我知道我必须多做一些才能知道学生的生日是否已经过去,但这不是我的问题的重点)。

重点是有些会很好,有些会以 NaN 形式出现

@Component({
  selector: 'app-students',templateUrl: './students.component.html',styleUrls: ['./students.component.css']
})
export class StudentsComponent implements OnInit {

  students: Character[]= [];
  
  constructor(private hogwartsService: HogwartsService) { }

  ngOnInit(): void {
    this.getStudents();
  }

  getStudents(){
    this.hogwartsService.getStudents().subscribe(response => {
      this.students = response;
      console.log(this.students);
    });
  }
}

为什么会这样?为什么有些以数字形式出现,而有些以 NaN 形式出现?

解决方法

因为传递的日期格式 31-07-1980 是错误的。你应该像这样通过MM-DD-YYYY。因此,您需要先格式化 dateOfBirth,然后再将其传递给 Date()

Javascript DateTime Formats

// NaN
console.log(new Date().getFullYear()  -  new Date("31-07-1980").getFullYear());

// Valid
console.log(new Date().getFullYear()  -  new Date("07-31-1980").getFullYear());

使用 Moment.JS

使用 Moment.JS 您可以指定输入日期格式。处理多种日期格式要容易得多。

const day = moment("31-07-1980","DD-MM-YYYY");

适合您的替代解决方案

我在提供的 API 响应中找到了 yearOfBirth。那么你为什么不使用它来计算这样的年龄,

const age = new Date().getFullYear()  -  respItem.yearOfBirth;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。