Having trouble converting the JSON object received from the server into the necessary type to analyze the data

I am new to angular and struggling with converting a JSON object from the server into a custom datatype to render in HTML using ngFor. Any help would be appreciated as I have tried multiple approaches without success.

Apologies for the simple HTML page, I am focusing on functionality and backend connections before working on design.

Below is the code snippet and attached screenshots for reference.

Employee.Component.html

<p>Inside Employee Component.</p>
<button type="submit" class="btn btn-login float-center" (click)="getAllEmployees1()">getAllEmployees</button>

<div>
    <h2>Employee List</h2>
     {{ employees }}
  </div>
employee.component.ts file

employees: any;

 constructor(private service: EmployeeServiceService){
  }
  ngOnInit(){

  }

  public getAllEmployees1(){
    this.service.getAllEmployees().subscribe((data)=>{

      this.employees = data;
      console.log("Response: "+ this.employees);
    },
    (error) =>{
      console.error('Error fetching employees: ', error);
    }
    );
  }
EmployeeService file:

@Injectable({
  providedIn: 'root'
})
export class EmployeeServiceService {

  constructor(private http:HttpClient) { }

  getAllEmployees(){
    console.log("Inside get ALL Employees Method.");
    return this.http.get("https://localhost:9090/employee/getAllEmployees",{responseType:'text' as 'json'});
  }
Employee class type:

export class AddEmployee{
    firstName: any;
    lastName: any;
    address:any;
    project:any
    ssn:any;
    joinDate:any;
    status:any

        constructor(
            firstName: string,
            lastName: string,
            address:string,
            project:string,
            ssn:number,
            joinDate:Date,
            status:number
        ){}
    }

I am trying to convert the server's JSON data to AddEmployee type for displaying in a tabular format using ngFor. Angular is showing errors that the data is in Object Format and ngFor can only be used on observables and iterators. Attached is an image showing the object returned from the server when I click on the getAllEmployees button.

enter image description here

Error Page: https://i.sstatic.net/n6IAK.png

Answer №1

The reason for the issue is that you must initialize the employees variable as an empty array. This is necessary because the code runs initially on the first load, and only after the button is clicked does the array get set.

employees: any = [];

For a working example, you can refer to the mock stackblitz provided below. Some key points to keep in mind are:

  1. If the service is provided at the root level, then you need to inject the dependencies

as shown below.

private http = Inject(HttpClient);

service

import { HttpClient } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { of } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class TestService {
  private http = Inject(HttpClient);
  constructor() {}

  getAllEmployees() {
    console.log('Inside get ALL Employees Method.');
    return of([
      {
        firstName: 'test',
        lastName: 'test',
        address: 'test',
        project: 'test',
        ssn: 'test',
        joinDate: 'test',
        status: 'test',
      },
      {
        firstName: 'test',
        lastName: 'test',
        address: 'test',
        project: 'test',
        ssn: 'test',
        joinDate: 'test',
        status: 'test',
      },
      {
        firstName: 'test',
        lastName: 'test',
        address: 'test',
        project: 'test',
        ssn: 'test',
        joinDate: 'test',
        status: 'test',
      },
      {
        firstName: 'test',
        lastName: 'test',
        address: 'test',
        project: 'test',
        ssn: 'test',
        joinDate: 'test',
        status: 'test',
      },
    ]); //this.http.get("https://localhost:9090/employee/getAllEmployees",{responseType:'text' as 'json'});
  }
}

main.ts

import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { AddEmployee } from './add-employee';
import { TestService } from './test.service';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [HttpClientModule, CommonModule],
  template: `
    <p>Inside Employee Component.</p>
<button type="submit" class="btn btn-login float-center" (click)="getAllEmployees1()">getAllEmployees</button>

<div>
    <h2>Employee List</h2>
     {{ employees  | json}}
     
     <table border="1">

  <thead>
    <th *ngFor="let column of columns">
      {{column}}
    </th>
  </thead>

  <tbody>
    <tr *ngFor="let row of employees; index as i">
      <td *ngFor="let column of columns; index as j">
        {{row[column]}}
      </td>
    </tr>
  </tbody>

</table>
  </div>
  `,
})
export class App {
  columns = [
    'firstName',
    'lastName',
    'address',
    'project',
    'ssn',
    'joinDate',
    'status',
  ];
  employees: Array<AddEmployee> = [];

  constructor(private testService: TestService) {}
  ngOnInit() {}

  public getAllEmployees1() {
    this.testService.getAllEmployees().subscribe({
      next: (data) => {
        this.employees = data;
        console.log('Response: ' + this.employees);
      },
      error: (error) => {
        console.error('Error fetching employees: ', error);
      },
    });
  }
}

bootstrapApplication(App);

Check out the stackblitz example here

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

Error encountered while bundling CDK Synth with Node.js function - Kindly ensure to update your lock file by running `npm install` before proceeding further

As I attempt to utilize AWS CDK for creating a Lambda function, I am facing a challenging error: "npm ERR! npm ci can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are in sync. Please update your lock file ...

How can I display the top 5 data results after subscribing in Nativescript?

Utilizing this function allows me to retrieve all my data from the web service. public data: Data[]; getall() { this.ws.getalldata().subscribe( data=> { this.data= data; } ); } Here is a ...

What is the specific type of event for a change handler in TypeScript?

As a newcomer to TypeScript, I recently crafted a change handling function that accepts the event as a parameter to assign the value, like event.target.value. Currently, I have designated this as any, but I suspect there is a more appropriate type for this ...

I encountered the error message "The property you are trying to access does not exist on the type 'never'" while attempting to retrieve JSON data from the API response

Every time I attempt to access the fields in items such as id or title, an error pops up saying Property does not exist on type 'never'. Interestingly, when I log the data using console.log(response.data), everything seems to be working fine. I ...

Obtain characteristics of the primary element in Ionic version 2 or 3

After creating and opening my Sqlite database and saving the SQLiteObject in a variable within my app.component.ts, I now need to retrieve these attributes in my custom ORM. The ORM extends to other providers to describe the title and field of my tables. ...

Utilizing TypeScript's Type Inference to Simplify Function Combinations

I'm facing a challenge with what should be simple. The types aren't coming through as expected when trying to combine a couple of functions. Is there a way to have TypeScript infer the types without explicitly specifying them? import { pipe, map ...

Tips for troubleshooting the error "Cannot locate module mp3 file or its associated type declarations"

https://i.sstatic.net/q4x3m.png Seeking guidance on resolving the issue with finding module './audio/audio1.mp3' or its type declarations. I have already attempted using require('./audio/audio1.mp3'), but continue to encounter an error ...

Issue with rendering HTML tags when replacing strings within Ionic 2 and Angular 2

I am currently working with an array of content in my JSON that includes URLs as plain text. My goal is to detect these text URLs and convert them into actual clickable links. However, I'm facing an issue where even though the URL is properly replaced ...

The Ionic tab is already finished displaying even before the data has completed loading

Creating a favorites section for a vouchers app has proven to be slightly challenging. When attempting to retrieve the current user's favorite vouchers and display them using ngFor in the HTML, I encountered an issue. The very first time I open the fa ...

Encounter an Unexpected Token Issue when using NextJS-auth0 in Jest

I am facing a problem with my Next.js app that is integrated with the nextjs-auth0 package. Whenever I attempt to test a particular file and include the following import: import { getSession } from '@auth0/nextjs-auth0'; An error occurs, stating ...

Visual Studio Code is encountering issues when trying to start a Node application

I am in the process of setting up a workflow for an express app using TypeScript, Visual Studio Code, and gulp. Here is the structure of my project: src/ <-- source files Start.ts Server.ts models/ Contact.ts Organization.ts bin/ <- ...

Exploring child components through auxiliary routing in Angular

After defining the root routing as shown below: const routes: Routes = [{ path: '', component: HomeComponent }, { path: 'module1', loadChildren: './module1/module1.module#Module1Module' }, { path ...

Is it possible to retrieve messages from a service bus using an Angular app without relying on SignalR?

In our app, we are looking to post messages from our backend to an azure service bus in order to avoid waiting for a long process. Is it possible to do this directly from the front end, or do we need to implement a signalR solution with additional steps on ...

Cell renderers in Angular do not receive the ICellRendererParams during initialization

I am currently working on creating a cell renderer in Angular that converts IP addresses into clickable SSH links. Below is the code for the renderer component: import { Component, OnInit, OnDestroy } from "@angular/core"; import { DomSanitizer, ...

Arranging Typescript strings in sequential date format

Looking for guidance on how to sort string dates in chronological order, any expert tips? Let's say we have an array object like: data = [ {id: "1", date: "18.08.2018"} {id: "2", date: "05.01.2014"} {id: "3", date: "01.01.2014"} {id: ...

Deactivating attribute inheritance / configuring component settings with script setup and Typescript

Is there a way to disable attribute inheritance for a component's options when using script setup syntax with Typescript in Vue 3? Here is the JavaScript code example: app.component('date-picker', { inheritAttrs: false, // [..] }) How ...

Validating React components with TypeScript using an array structure where the field name serves as the key

Trying to implement form validation with React. I have a main Controller that contains the model and manages the validation process. The model is passed down to child controllers along with the validation errors. I am looking for a way to create an array ...

How can I programmatically trigger the optionSelected event in Angular Material's autocomplete?

I'm currently facing an issue with my Angular Autocomplete component. I am trying to trigger the (optionSelected) event within the ts file after a different event by setting the input with the updated option using this.myControl.setValue(options[1].va ...

Using @HostBinding based on the @Input() condition

I'm attempting to link the CSS class foo to my parent component by utilizing @HostBinding based on a condition I evaluate against a dynamic variable. However, I am struggling to get it to function as expected. Here are the different approaches I hav ...

Attaching the JSON data to ngModel in Angular 2

I have received a json response containing various fields, including the rewards.rewardName value. I'm trying to figure out how to bind this specific value to [(ngModel)] in Angular 2. [ { "id": 18, "gname": "learning ramayanam", "goalCat ...