Angular 4 yields an undefined result

I'm currently working on this piece of code and I need help figuring out how to return the value of rowData in this scenario.

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

Before returning, I attempted to console log rowData but it returned undefined.

Answer №1

Your function must provide a promise that contains the transformed data. In the final then callback, make sure to return the transformed response. Utilize the implicit return of arrow functions for this purpose without needing the variable rowData since array.proptype.map generates a new array with each value transformed. Simply follow these steps:

private fetchTransformedData() {
   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,
     })));
}

You can then utilize this function in the following way:

this.fetchTransformedData().then(result => console.log(result))

Answer №2

When you make an asynchronous http call, it's crucial to handle the data retrieval properly to avoid getting undefined values. One common mistake is executing the return rowData; line before the call is complete, resulting in an incomplete response. To fix this issue, consider returning a promise from your function and utilizing a .then() call to fetch the rowData object once the operation is finished.

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

  return this.http  
   .get(`/assets/json/data.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;
    });
  });

}

ngOnInit() {
  this.fetchData().then(data => {
    console.log(data) 
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to create a modal as a standalone component in Angular 2?

I recently discovered this library https://github.com/dougludlow/ng2-bs3-modal which allows me to create modals in Angular 2. For my application, I specifically need the modal to be in a separate component. Here is an example : a.component.html contains ...

Encountering the error message `TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"` with `ts-node` when the type is specified as module

After configuring absolute paths in my Express project and changing the type to module for using import, I encountered an error: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" Below is the content of my tsconfig.json { &q ...

Tips for sending information to an API using the HttpClient POST technique

When attempting to send data to an API using the HttpClient POST method, only an empty array is being passed. sendData(input){ this.httpClient.post('http://localhost/tasker/api/index.php/insert_users', { data: input, tt: 'tt ...

TypeScript's standard React.Children interface for compound components

One of my components is a Table, which can have children that are Column components: <Table data={data}> <Column cell={(c) => c.date} header="Date" /> <Column cell={(c) => c.count} header="Count" /> & ...

Unlock the Power of Typography in React with Material UI Styled Components

Exploring the world of material UI is a new experience for me. I am currently in the process of creating a styled component using Typography. Below is what I have attempted so far: import styled from 'styled-components'; import { FormGroup, ...

How to access NavController in an Ionic2 service provider

In my Ionic2 app, I have created an AuthHttpProvider which acts as a wrapper for Http requests and automatically adds an authentication token (jwt) to each request. I use this instead of the default Http provider in all of my interactions with the server. ...

Tips for transferring parameters between components: leveraging the ? and & operators within URLs

Is there a way to pass parameters between components other than using ActivatedRoute? Currently, I am utilizing ActivatedRoute. In component1.ts this.router.navigate(['/rate-list', 1]); In app.module.ts { path: 'rate-list/:a', pathM ...

When executing the command "ng serve" in Angular, the following error is displayed: "webpack: Compilation failed."

I am currently using Mac OS (10.11.6) and have been attempting to familiarize myself with Angular. I successfully installed node.js, typescript, and angular-cli, and everything seemed to be functioning properly. However, whenever I executed "ng serve", it ...

Refreshing the webpage upon submitting with Angular2 and Firebase technology

Yesterday, I came across an Admin HTML template that I wanted to integrate with Firebase. However, when I tried to register and clicked on Sign in, the page would reload instead of carrying out the Firebase createUserWithEmailAndPass process. Here is a s ...

Angular4 allows for the creation of a div that can horizontally scroll

Below is the HTML code I am working with: <div class="card-deck" fxLayout.xs="row" style="overflow: scroll; height:100%"> <md-card style="width:10rem" *ngFor="let make of filteredMakes" (click)="goToModels(make.niceName)" class=" ...

Struggling to transfer information between different components?

I recently implemented a delete button functionality in my project to remove elements when clicked, but I'm facing an issue where the input decorator is not properly receiving data for deletion. When I console log, it shows that the array is empty whi ...

Transferring data between pages in Next JS using App Route and Typescript

Seeking assistance to extract data from an array on one page and display it on another page. I am working with NextJs, Typescript, and AppRoute. Code in app/page.tsx: import Image from 'next/image' import Link from 'next/link' const l ...

Angular component receives only initial value from BehaviorSubject

I am facing an unusual issue where I have created a service to emit the value of the item clicked on the navbar in order to trigger a modal. import { EventEmitter, Injectable } from "@angular/core"; import { BehaviorSubject, Subject } from " ...

Guide to displaying the value of a field in an object upon clicking the inline edit button using TypeScript

Is it possible to console log a specific attribute of an object when clicking on the edit button using the code below? Please provide guidance on how to utilize the index to access the value of "name". Refer to the last line in the code with the comment. ...

ngOnChange event not firing despite attempting various solutions

My goal is to utilize ngOnChanges to update a string (even or odd) after another variable (counter) changes. However, I am encountering an issue where the value of the message remains blank and does not update when the counter changes. export class Counter ...

In Angular, set the default value of the first item in the list to be highlighted when the page loads

In my project, there are two key components: 1)contact and 2)display. The contact component is responsible for displaying a list of contacts as shown in the image below: Next to the contact component, I have placed another component called 'display& ...

What is the best way to transform HeadersInit into an Object<string,string> data type?

In short, I am faced with the task of converting the headers of a RequestInit into a format that another library can comprehend. This particular library requires the headers to be in the format of Object<string, string>. Initially, I attempted someth ...

Steps to implement two-way binding in mat-select feature

Here is the code snippet I am working with: <mat-form-field> <mat-select [(ngModel)]="valueFromDB.name"> <mat-option>None</mat-option> <mat-option *ngFor="let option of options" [value]="option. ...

Is it possible to assign a type conditionally depending on the value of a boolean?

While grappling with this issue, the title question arose in my mind: How can I handle the situation where the library function getResponse returns { a: number } for Android phones and { b: number } for iOS phones? The code snippet below initially led to ...

Combining two objects by aligning their keys in JavaScript

I have two simple objects that look like this. var obj1 = { "data": { "Category": "OUTFLOWS", "Opening": 3213.11, "Mar16": 3213.12, "Apr16": 3148.13, "May16": 3148.14, "Jun16" ...