Error: Angular - encountering undefined response when making HTTP request

When making a HTTP GET request to my backend, it returns the following JSON data:

    "{\"instID\":\"2018#10#30\",\"procID\":1161006,\"threadNum\":0,\"status\":2}",
    "{\"instID\":\"2018#10#30\",\"procID\":1161021,\"threadNum\":0,\"status\":2}",
    "{\"instID\":\"2018#10#30\",\"procID\":1161031,\"threadNum\":0,\"status\":2}"

I need to set this data to an interface so that I can display it in an HTML table later on.

The Interface:

export interface IliveLog {
    instID: string;
    procID: number;
    threadNum: number;
    status: number;
}

Backend HTTP Service:

import { Injectable } from "@angular/core";
import 'rxjs/Rx';
import { Observable } from "rxjs/Rx";
import { HttpClient } from "@angular/common/http";
import { IliveLog } from "../jobs/live-log/log.interface";


@Injectable()
export class BackEndService {
    constructor(private http: HttpClient) { }

    getAgentStatus(): Observable<IliveLog[]> {
            return this.http.get<IliveLog[]>('http://localhost:8081/rms_agent/status');
        }
}

Live-Log Component:

export class LiveLogComponent implements OnInit {

private dataMaster: IliveLog[] = new Array();//Observable<IliveLog[]>;
private dataAgent: IliveLog[] = new Array();//Observable<IliveLog[]>;

constructor(private backend: BackEndService) { }

ngOnInit() {
  setInterval(() => {
    this.onGetMaster();
    this.onGetAgent();
  }, 500);
}

onGetAgent() {
  this.backend.getAgentStatus().subscribe(
    response => {

      // Just for testing purposes
      for (const i of response) {
        console.log('instID: ' + i.instID);
        console.log('procID: ' + i.procID);
        console.log('threadNum: ' + i.threadNum);
        console.log('status: ' + i.status);
      }

      for (let i=0; i<response.length; i++)
      {
        this.dataAgent.push({instID: response[i].instID, procID: response[i].procID, threadNum: response[i].threadNum, status: response[i].status});
        console.log("response[i].instID = " + response[i].instID);
      }

      /* this.dataAgent = response;
      console.log("Agent: " + this.dataAgent); */
    }
  )
}

HTML:

<p>Running on Agent:</p>
<table border="1">
  <thead>
    <td>instID</td>
    <td>procID</td>
    <td>threadNum</td>
    <td>status</td>
  </thead>
  <tbody>
    <tr *ngFor="let item of this.dataAgent">
      <td>{{item.instID}}</td>
      <td>{{item.procID}}</td>
      <td>{{item.threadNum}}</td>
      <td>{{item.status}}</td>
    </tr>
  </tbody>
</table> 

 <p *ngIf="this.dataAgent">{{ this.dataAgent }}</p>
<button class="btn btn-success" [disabled]="true">start</button>
<button class="btn btn-danger" [disabled]="true">kill</button>
<button class="btn btn-info" [disabled]="true">log</button>
<hr>

The issue I'm facing is that when trying to list the objects in my HTML table, they are showing as undefined: Console LOG

Here is the result displayed in the HTML table: HTML table result

Why am I not getting the response in the desired format according to my interface? Could it be an issue with the backend implementation? Check out this example of console.log(response) for reference: Example of console.log(response)

My JAVA Backend Code:

// pe/status
static class StatusHandler implements HttpHandler {

    ProcessManager pm;

    public StatusHandler(ProcessManager pm) {
        this.pm = pm;
    }

    public void handle(HttpExchange httpExchange) {

        try {        
            // Get Processes status
            HashMap<String,ProcessTask> currProcs = pm.getRunningProcs();

            JSONArray rspBuilder = new JSONArray();


            // If not empty
            if (!currProcs.isEmpty()) {

        // Iterate
        Collection<ProcessTask> procList = currProcs.values();
        if (procList != null && !procList.isEmpty()) {
                    for (ProcessTask pt : procList) {

                        JSONObject procBuilder = new JSONObject();

                        procBuilder.put("procID",pt.getProcID());
                        procBuilder.put("instID",pt.getInstID());
                        procBuilder.put("threadNum",pt.getThreadNum());
                        procBuilder.put("status",pt.getStatus());

                        rspBuilder.put(procBuilder.toString());

                    }
                 }
            }

            // build response
            String response = rspBuilder.toString();

            httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
            httpExchange.sendResponseHeaders(200, response.length());
            OutputStream os = httpExchange.getResponseBody();
            os.write(response.getBytes());
            os.close(); 
        } catch (Exception ex) {
            LogUtils.log(LogUtils.LOG_ERROR,"[ WS StatusHandler ]  Error Message - " + ex.getMessage() );
        }
    }

} 

Answer №1

The issue primarily lied in the backend system, where it was generating a string instead of an object.

To confirm and troubleshoot this, I utilized JSON editor online to verify the JSON structure and found that the response did not align with my expectations.

To resolve this, I modified the backend logic to return an array containing objects rather than strings.

Update: Another approach could involve converting the string data into objects for processing.

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 process for converting/executing TypeScript into JavaScript?

Having trouble running https://github.com/airgram/airgram Encountering this warning message from the post (node:9374) Warning: To load an ES module, set "type": "module" Have already added {"type": "module"} To pa ...

Trying out tess4j to recognize text and encountering the UnsupportedClassVersionError

Seeking to experiment with tess4j in Eclipse, I ran into an UnsupportedClassVersionError even after following a tutorial. The error message mentions that net/sourceforge/tess4j/TesseractException has an unsupported major.minor version 51.0. I am currently ...

Checking the text both before and after clicking a link by using a method such as content verification

Currently, I am encountering an issue with validating the text on my links before and after they are clicked. If the link text reads "one two" before clicking and remains as "one two" after the click, then the test case passes. However, if the text change ...

Troubleshooting Angular directives and the complications of closures

I am facing a problem with this specific directive: @Directive({ selector: '[imgTest]', }) export class ImgTest implements AfterViewInit, OnDestroy { private originalImage: HTMLImageElement; private secondImage: HTMLDivElement; construc ...

The error message "Error: cannot read property ‘setDirtyAttribute’ of null" may be encountered when attempting to use the method YourModel.create({...}) in ember-typescript-cli

Encountering the error cannot read property 'setDirtyAttribute' of null even when using YourModel.create({...}) in ember-typescript-cli to instantiate an EmberObject. Model: import DS from 'ember-data'; import {computed} from "@ember/ ...

The connection of <p:ajax> to a parent component that is not a ClientBehaviorHolder is not possible

Trying to trigger a function when selecting a value from a dropdown. See the code below: <h:form id="frmUpload" enctype="multipart/form-data"> <p:column><h:outputText value="Select Team: " /></p:column> <p:colu ...

At what point is it appropriate for a class to incorporate an interface?

Currently working on a project and I've noticed developers using TypeScript in the following way: export class Ledger implements ILedger { LedgerID: number; CashAmmount: number; Units: number; ...

Working with JSON and incorporating embedded objects in Powershell

The output from my JSON file obtained using ConvertFrom-Json is as follows: Id : 1 ItemName : TestFile SharingInformation : {@{<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7e5d2d4dec7ded2d9c3f2dad6d ...

Error message displaying Angular Service not able to be injected into component: StaticInjectorError in AppModule

I'm currently attempting to inject a SpotifyService service into a SearchComponent component, where the service requires Http as a parameter. Below is my module setup: @NgModule({ imports: [ BrowserModule, FormsModule, RouterModule ], decla ...

JSON is not conforming to the standard nesting level

After simplifying, the JSON implementation is as follows: Data(Entity)->"data"->another Entity I originally thought I could decrypt the Data object first, extract a type from it, and then use that type to decrypt the necessary type from the String ...

Exploring the capabilities of pandas when working with json normalization

I have a simple JSON structure that I'm trying to normalize. data = [{"pedido": {"situacao": "OK", ....}}, {"pedido": {"situacao": "NOK", ...}}] rs = json_normalize(data, 'pedido& ...

Navigating using the Angular router occurs before any other lines of code are executed

I am encountering an unusual issue with my Angular code involving a login page that interacts with an API. login.component.ts: export class LoginComponent implements OnInit { formData; constructor(private usersService: UsersService, private router: ...

What is the reason behind Gson anticipating an array at the start but receiving an object instead?

I have encountered an error while using this JSON data to fetch articles with Retrofit: Received an error message: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 Below is the code I am working on: RestAdapter restAdapter = new RestAdapte ...

Enhanced security by implementing longer cipher length for AES encryption using Integer array

Within this code snippet, I have utilized an integer array to carry out AES encryption. The input consists of an integer array with a size of 16 elements. Upon encryption, the resulting cipher byte[] size is 64. It's worth noting that each integer occ ...

``Can someone provide guidance on how to showcase the validation check result for a text-field in the snackbar using Vuet

One of the challenges I'm facing in my project is implementing a validation function for the customer form. While using the vuetify validate method would be the easy way to go, I need to display the validation messages both as snackbar and next to eac ...

Steps to set up Node.js Express.js for API, React.js for the front end, and Angular for the admin panel

Is there a way to deploy nodejs with SSL certificates? I am using expressjs for API, reactjs for front-end, and angular for backend. I need specific paths like for frontend, for admin, and the expressjs API running in the background with https, similar t ...

Problem with organizing data by dates

My timers list looks like this: timer 1 => { startDate = 17/01/2019 11PM, endDate = 18/01/2019 9AM } timer 2 => { startDate = 18/01/2019 7AM, endDate = 18/01/2019 1PM } timer 3 => { startDate = 18/01/2019 12PM, endDate = 18/01/2019 10PM } time ...

What is the approach of Angular 2 in managing attributes formatted in camelCase?

Recently, I've been dedicating my time to a personal project centered around web components. In this endeavor, I have been exploring the development of my own data binding library. Progress has been made in creating key functionalities akin to those f ...

"Exploring the world of Typescript with the Drawflow library

Currently, I am integrating the fantastic Drawflow library created by @Jerosoler (available at: https://github.com/jerosoler/Drawflow) into my PrimeNg project. User @BobBDE has provided typescript definitions for this library here: https://www.npmjs.com/p ...

Converting hierarchical JSON data into a table with rowspan using Angular

I am facing a challenge in creating a table using nested JSON obtained from an API. I am unsure how to dynamically merge cells when needed, especially since the JSON structure can be nested up to 6 or 7 levels. Desired Table : Expected Table Current Ou ...