首页 > 解决方案 > 显示数据时未定义

问题描述

结果,当我想显示数据时,我得到undefined

这只发生在进度数组中。

其余数据不存在这样的问题。

为什么会发生这种情况,我该如何解决?

console.log(this.splineChart)

[{…}]
  0:
   data: Array(1)
     0: Array(2)
       0: undefined
       1: undefined

ts:

  user: User[];
  splineChart = [];

  load() {
    this.route.params
      .pipe(
        switchMap(
          (params: Params) => {
            if (params['id']) {
              return this._peopleService.getPeopleById(params['id'])
            }
            return of(null)
          }
        )
      )
      .subscribe(
        (user: User[]) => {
          this.splineChart = [{
            data: user.map(function (item) {
              return [item.progress.tasks, item.progress.week]; 
          })}]
        },
        error => {
          console.log(error)
        }
      )
  }

我的 json 文件::

{
    "users": [
        {
            "id": 1,
            "fname": "Tommie",
            "lname": "Shurtleff",
            "photo": "tommie",
            "money": "667.16",
            "progress": [
                {
                    "id": 1,
                    "week": 1,
                    "tasks": 29
                },
                ...
            ]
        }
    ]
}

标签: angular

解决方案


Progress 是一个数组,您将其视为对象。item.progress.tasks这不适用于数组。

你必须循环item.progress获得期望的结果。

将您的订阅部分替换为以下内容。

this.splineChart = [{
   data: user.map(function(item) {
     return item.progress.map(progress => [progress.tasks, progress.week]);
   })
}];

请参阅下面的示例。

const user = [{
  "id": 1,
  "fname": "Tommie",
  "lname": "Shurtleff",
  "photo": "tommie",
  "money": "667.16",
  "progress": [{
      "id": 1,
      "week": 1,
      "tasks": 29
    },
    {
      "id": 1,
      "week": 2,
      "tasks": 30
    },
  ]
}];

let splineChart;
this.splineChart = [{
  data: user.map(function(item) {
    return item.progress.map(progress => [progress.tasks, progress.week]);
  })
}];

console.log(this.splineChart)


推荐阅读