首页 > 解决方案 > Angular 2+ / Typescript 无法读取未定义的属性

问题描述

我正在使用 Angular 7,并且从服务中获取这些数据:

{name: "peter", datetime: 1557996975991}

然后我有这个获取数据的方法:

myMethod() {

    this.myService.getdata().subscribe((res) => {

      console.log(res); // returns: {name: "peter", datetime: 1557996975991}

      console.log(res[0].datatime); // Gives Error: Cannot read property 'datetime' of undefined 

    }); 

}

当我尝试获取数据时间值时,我得到:

给出错误:无法读取未定义的属性“日期时间”

我怎样才能解决这个问题?

标签: angulartypescript

解决方案


res 变量是对象而不是数组。

您需要更改为console.log(res.datatime);

改成

myMethod() {

    this.myService.getdata().subscribe((res: any) => {

      console.log(res); // returns: {name: "peter", datetime: 1557996975991}

      console.log(res.datatime);

    }); 

}

推荐阅读