1

This is my current code. How can I return rowData value in this case?

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;}

I had tried to console rowData before return and it gave me undefine.

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
Jim
  • 91
  • 2
  • 12
  • 3
    Possible duplicate of [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) (TL;DR: You can't. You need to return the promise created by the last `.then` call) – Joe Clay Nov 15 '17 at 09:53

2 Answers2

2

Your method should return a promise of the transformed data. In the last then callback, you should return the transformed response. You can rely on the implicit return of arrow function to do that. You don't need the variable rowData because array.proptype.map returns a new array which each value in it is transformed. All you have to do is:

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,
     })));
}

Then you can use this methode like below:

this.createRowData().then(rowData => console.log(rowData))
Faly
  • 13,291
  • 2
  • 19
  • 37
1

You are making an asynchronous http call. The call is incomplete when the return rowData; line is executed, and hence you get undefined. To resolve this, return a promise from your function and use a .then() call to retrieve rowData from wherever you are calling your function.

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
  });
}
Aamir Khan
  • 2,945
  • 2
  • 25
  • 32