未定义的Angular 4返回值

时间:2017-11-15 09:52:45

标签: angular typescript

这是我目前的代码。在这种情况下如何返回rowData值?

private createRowData() {
const rowData: any[] = [];

this.http
  .get(`/assets/json/payment.json`)
  .toPromise()
  .then(response => response.json())
  .then(data => {
    data.items.map(elem => {
      rowData.push({
        id: elem.id,
        total_amount: elem.total_amount,
        status: elem.status,
        sent: elem.sent,
      });
    });
  });
return rowData;}

我曾经尝试在返回之前控制rowData,它给了我undefine。

2 个答案:

答案 0 :(得分:2)

您的方法应该返回转换数据的承诺。在最后一个回调中,您应该返回转换后的响应。你可以依赖于箭头函数的隐式返回来做到这一点。您不需要变量rowData,因为array.proptype.map返回一个新数组,其中的每个值都被转换。您所要做的就是:

private createRowData() {
   return this.http    // Return the promise
    .get(`/assets/json/payment.json`)
    .toPromise()
    .then(response => response.json())
    .then(data => data.items.map(elem => ({   // Return the transformed data by the then callback
        id: elem.id,
        total_amount: elem.total_amount,
        status: elem.status,
        sent: elem.sent,
     })));
}

然后您可以使用如下所示的方法:

this.createRowData().then(rowData => console.log(rowData))

答案 1 :(得分:1)

您正在进行异步http呼叫。执行return rowData;行时调用不完整,因此未定义。要解决此问题,请从您的函数中返回一个承诺,并使用.then()调用从您调用函数的任何地方检索rowData

private createRowData() {
  const rowData: any[] = [];

  return this.http  // <- Return promise
   .get(`/assets/json/payment.json`)
   .toPromise()
   .then(response => response.json())
   .then(data => {
     data.items.map(elem => {
      rowData.push({
        id: elem.id,
        total_amount: elem.total_amount,
        status: elem.status,
        sent: elem.sent
      });
      return rowData;
    });
  });
 //return rowData; // <- This is undefined because the call isn't complete yet
}

ngOnInit() {
  this.createRowData().then(data => {
    console.log(data) // <- rowData
  });
}