【问题标题】:Populating an array from a JSON during a promise [duplicate]在承诺期间从 JSON 填充数组 [重复]
【发布时间】:2021-08-11 09:40:59
【问题描述】:

我正试图将我的头脑围绕着承诺并有一些问题。 我有一个由许多条目组成的 JSON 数组:

  { "Work Date"  : "08/04/2021"
  , "Work type"  : "Working"
  , "Project"    : "Projectname"
  , "Client"     : "Company"
  , "Employee"   : "John Doe"
  , "Work hours" : "2.5"
  , "Work note"  : "Work notations here"
  , "Task"       : ""
  , "Task Name"  : ""
  , "TaskType"   : ""
  },

特别有兴趣将员工提取到数组中。所以我可以更容易地呈现/格式化。 这是我的 dataProvider Service (Angular),它加载 JSON 并提供数据以供进一步使用:

export class DataproviderService {
  effortsList:Effort[]
  employeeList:string[]
  constructor(private http: HttpClient) { }

  getData(){
    return this.http.get<any>("assets/data.json")
    .toPromise()
    .then(res => <Effort[]>res.data)
    .then(data => { 
      data.forEach(employee => this.employeeList.push(employee["Employee"]))
      return this.effortsList = data.slice();
     })
  }
}

不幸的是,这并没有像我想象的那样工作。我收到一个未捕获的错误:

未捕获(承诺):TypeError: this.employeeList is undefined

我做错了什么?提前谢谢!

【问题讨论】:

  • 您忘记将员工列表初始化为空数组,所以您的推送不起作用。
  • 旁注:你为什么将请求的返回类型定义为any,只是为了稍后将其转换为Effort[]?为什么不只是this.http.get&lt;Effort[]&gt;("assets/data.json").then(({ data }) =&gt; ... )

标签: javascript arrays json angular promise


【解决方案1】:

您的employeeList 未初始化。你只声明了它,没有赋值。

你也可以在做的时候简化你的代码

getData(){
  return this.http.get<any>("assets/data.json").toPromise()
    .then(res => { 
      const data = <Effort[]>res.data;
      this.employeeList = data.map(e => e.Employee);
      return this.effortsList = data.slice();
     })
  }
}

还要注意,toPromise 已被弃用,很快将被删除。 https://indepth.dev/posts/1287/rxjs-heads-up-topromise-is-being-deprecated

【讨论】:

  • 非常感谢您的投入。这看起来更干净。
【解决方案2】:

您忘记初始化您的effortsListemployeeList,所以它们都是undefined,这意味着您不能在它们上调用数组方法。

export class DataproviderService {
  effortsList: Effort[]
  employeeList: string[]
  constructor(private http: HttpClient) {
    this.effortsList = []
    this.employeeList = []
  }

  getData() {
    return this.http.get < any > ("assets/data.json")
      .toPromise()
      .then(res => < Effort[] > res.data)
      .then(data => {
        data.forEach(employee => this.employeeList.push(employee["Employee"]))
        return this.effortsList = data.slice();
      })
  }
}

另外,这条线不是一个好方法:

data.forEach(employee => this.employeeList.push(employee["Employee"]))`

我建议你改成这样:

this.employeeList = data.map(employee => employee["Employee"])

这样您将确保您永远不会将相同的项目从数据推送到您的 employeeList(例如,如果您将调用 getData 两次)。

【讨论】:

  • 哦,你说得对。我怎么会错过这个。非常感谢!
猜你喜欢
  • 2021-09-30
  • 1970-01-01
  • 2018-03-19
  • 1970-01-01
  • 2018-01-11
  • 2017-01-19
  • 2019-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多