Dividing a JSON object into arrays containing keys and values within an Angular framework

I have a code snippet that involves receiving a JSON object of type Tenant from an API. I need to separate this object into keys and values within my function called tenantParser(). However, when I try to log displayedValues and displayedKeys, both show an array with a length of 0. I'm unsure of where the issue lies in my code.

import { Component, OnInit } from '@angular/core';
import { ApiServiceService } from 'src/app/Services/api-service.service';
import { Tenant } from 'src/app/class/tenant';
    
    
@Component({
  selector: 'app-datawrangling',
  templateUrl: './datawrangling.component.html',
  styleUrls: ['./datawrangling.component.css']
})

export class DatawranglingComponent implements OnInit {
  
  displayedValues:any=[];
  displayedKeys:any=[]
  tenants!: Tenant[];
  tags: any;

  constructor(private apiService:ApiServiceService) { }

  ngOnInit(): void {
     this.apiService.sendGetRequest().subscribe ( data => {
       this.tenants = data; 
      console.log(this.tenants);
    });
     
     console.log(this.displayedValues)

  } 

  tenantParser(){
   this.tenants.forEach((element:any )=> {
      
      this.displayedValues=Object.keys(element);
     this.displayedKeys.push(Object.values(element));
   });

    this.ngOnInit()

    alert(this.displayedData)   
  }

} 

Answer №1

Make sure to invoke the tenantParser() function only after the request has been completed, within the subscribe() method. Avoid calling ngOnInit from tenantParser().

Additionally, double check if the assignment of Keys and Values in your code aligns with your intended logic. Is that intentional?

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 causes a BehaviorSubject to update when modifying the [(NgModel)] values of a form without actually submitting the form?

When I work with a form that relies on a BehaviorSubject to load user information, I noticed that if I make changes to the inputs but navigate away from the page without submitting the form, the user information gets updated in the subject automatically. ...

esBuild failing to generate typescript declaration files while running in watch mode

Recently dove into using edBuild and I have to say, it's been a breeze to get up and running - simple, fast, and easy. When I execute my esBuild build command WITHOUT WATCH, I can see that the type files (.d.ts) are successfully generated. However, ...

Setting up NextJs in Visual Studio Code with Yarn

When I used yarn create next-app --typescript to set up a TypeScript Next.js application with Yarn, everything seemed to be working fine with the command yarn run dev. However, Visual Studio Code was not recognizing any of the yarn packages that were added ...

What are the steps for creating a TypeScript version of a custom CKEditor5 build?

Currently, I am in the process of creating a personalized version of CKEditor5. By following the guidelines provided in the official documentation, I successfully obtained ckeditor.js. My goal now is to produce a typescript file (ckeditor.ts or ckeditor.d ...

Is there a way to include the present date and time within a mat-form-field component in Angular?

I'm working on a mat-form-field to display the current time inside an input field. I've managed to insert it, but I'm struggling with the styling. Here's the snippet of code I'm using: <mat-label>Filing Time:</mat-label> ...

How can the second subscription's return value be synchronously used in the first subscription in Angular 6?

Currently, I am working on an Angular 6 application and facing a scenario where I have to make multiple API calls in sequence, pass data between them, and then continue the process. For instance, in the .ts file: logout(){ this.apiService.POST({}, "logo ...

CPU usage spikes after launching a Cordova project in Visual Studio 2015 RTM

If you're looking for the source code of the project, you can find it at https://github.com/Yaojian/Ionic-TypeScript-Starter/. I decided to create a Visual Studio project by forking https://github.com/Justin-Credible/Ionic-TypeScript-Starter/ and fol ...

I'm attempting to retrieve an image from the database to display in the modal, but unfortunately the image isn't appearing as expected within the modal

I have the following code snippet for fetching an image: <img src="pics/file-upload-image-icon-115632290507ftgixivqp.png" id="image_preview1" class="img-thumbnail" style="margin-top: 15px; height:50%; width:20%"&g ...

Inquiring about the application of spread argument in TypeScript

Here is some code I'm working on: import _ from 'lodash'; function test(num1: number, num2: number) { console.log(num1, num2); } test(..._.take(_.shuffle([0, 1, 2]), 2)); I encountered a TS2556 error while using the TS playground and ...

I keep receiving multiple header errors from ExpressJS even though I am positive that I am only sending a single header

Can someone please help with the issue I'm facing in the code below: router.put("/:_id", async (req: Request, res: Response) => { try { // Create the updated artist variable const artist: IArtist = req.body; const updatedArt ...

A specialized type that guarantees a string union includes a particular string literal

I need to define a Mapped type that specifies a field named status which can be either a string or the string value ready: This example works as expected: export type ValidServiceState = HasReady<{ status: "ready" }>; The following should ...

Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the objec ...

What is the method for inserting an object into a jsonArray in TypeScript?

I am trying to add an object to existing JSON data in TypeScript. I am new to TypeScript and have created an array variable called jsonArrayObject, which contains a boolean[] type. This jsonArrayObject holds a contactModel object with properties like fname ...

Implement a universal Custom Validator to be applied to all FormControls across the entire application

We've encountered a scenario where a client proposed incorporating a custom validator to every field in their application, which comprises of over 1000 Angular formControls. I'm curious to know if there exists a method to universally alter the f ...

Best practices for organizing API Services using TypeScript and Next.js Server Actions

My product-actions/index file contains various server actions such as createProduct and getProductAssets, each of which verifies the user session before processing the request. I am looking for a way to check the session validity only once and then procee ...

Retrieving the location.host parameter within NgModule

I am currently working on integrating Angular Adal for authenticating my application's admin interface with Azure AD. However, I have encountered a challenge with the redirectUri setting. My goal is to dynamically retrieve the current app's host ...

Encountering NullInjectorError during Angular 5 Upgrade: InjectionToken LocaleId Provider Not Found

Recently, I made the transition from Angular 4 to Angular 5 using CLI 1.5.4 for my app. Along with that, I have a shared library set up via npm link. To successfully build my project after the upgrade, I had to make changes in my tsconfig.app.json file as ...

Encountering an Error When Trying to Run Npm Install in React-Native

I encountered an issue while trying to perform an npm install on my project, so I deleted the node modules folder in order to reinstall it. However, even after running npm install in the appropriate directory, I continued to face numerous errors in my term ...

Is there a way to seamlessly transition between different Angular components without having to refresh the entire webpage?

I'm currently working on implementing a navigation bar that allows users to switch between three components without having the navbar reload. The goal is for only the new component to load when the user clicks on a different section of the navbar, kee ...

Unable to bring in a TypeScript library that was downloaded from a GitHub fork repository

Currently, I am working on developing a GitHub app using the probot library. However, I have encountered an obstacle as outlined in this particular issue. It seems that probot does not offer support for ESM modules, which are crucial for my app to function ...