简体   繁体   中英

Angular - http response is undefined

I'm trying to make a http get request to my backend and it returns the following JSON:

    "{\"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'm trying set it to my interface so latter I can display it in a HTML table.

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 => {

      //apenas para ver como funciona
      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>

My log says that the objects are undefined and I can't list them in my html table: Console LOG

HTML table result

Why I can't get my response in type to my interface? Is the backend the problem?

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

} 

So the main problem was the backend. It was returning a string and not an object.

I used JSON editor online to validate the JSON and see that the response was not what I was expecting to get.

So what I done was change the backend to return an array with objects and not with strings.

Update : Also what could be done is parse the string to objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM