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.

1

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Get it. Thank you for your help! :)
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
  });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.