简体   繁体   English

Angular-HTTP响应未定义

[英]Angular - http response is undefined

I'm trying to make a http get request to my backend and it returns the following JSON: 我正在尝试向后端发出http get请求,并且它返回以下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. 我正在尝试将其设置为我的界面,以便后者可以将其显示在HTML表中。

Interface: 接口:

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

Backend http service: 后端http服务:

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: 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表中列出它们: 控制台LOG

HTML table result HTML表格结果

Why I can't get my response in type to my interface? 为什么我无法获得界面类型的回复? Is the backend the problem? 后端是问题吗?

Example of console.log(response). console.log(response)的示例。

My JAVA backend code: 我的JAVA后端代码:

// 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. 在线使用JSON编辑器来验证JSON,然后看到响应不是我期望得到的。

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. 更新 :另外,可以将字符串解析为对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 角度未定义Response.success - Response.success undefined in angular Angular 不显示从 http 响应收到的数据 - Angular not displaying data received from http response Angular 5:预检的响应具有无效的HTTP状态代码403 - Angular 5: Response for preflight has invalid HTTP status code 403 预检的响应具有无效的HTTP状态代码:401 angular - Response for preflight has invalid HTTP status code: 401 angular 本地主机api请求的HTTP失败响应:0未知错误-Angular - Http failure response for localhost api request: 0 Unknown Error - Angular 当执行POST HTTP方法时,eclipse将“ Response.status(Status.CREATED)”识别为“ Response”类型的未定义 - When performing a POST HTTP method the “Response.status(Status.CREATED)” is recognised as undefined for the type “Response” by eclipse Angular:http 的 Http 失败响应://localhost:8082/employee/all: 0 未知错误 - Angular : Http failure response for http://localhost:8082/employee/all: 0 Unknown Error UnCaught TypeError:无法在以下位置调用未定义的方法“ setAttribute”:-尝试显示HTTP响应时 - UnCaught TypeError : Cannot call method 'setAttribute' of undefined at - While trying to display HTTP Response HTTP 响应获取 html 响应 - HTTP response getting html response 响应http响应正文的编码 - encoding of response http response body
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM