【问题标题】:Angular - http response is undefinedAngular - http响应未定义
【发布时间】:2018-11-07 15:20:24
【问题描述】:

我正在尝试向我的后端发出 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}"

我正在尝试将其设置为我的界面,以便稍后我可以在 HTML 表格中显示它。

界面:

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

后端 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');
        }
}

实时日志组件:

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>

我的日志说对象未定义,我无法在我的 html 表中列出它们: Console LOG

HTML table result

为什么我的界面无法得到响应? 后端有问题吗?

Example of console.log(response).

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

} 

【问题讨论】:

    标签: java json angular typescript


    【解决方案1】:

    所以主要问题是后端。它返回的是一个字符串而不是一个对象。

    我使用JSON editor online 来验证 JSON,发现响应不是我所期望的。

    所以我所做的是将后端更改为返回一个包含对象而不是字符串的数组。

    更新:还可以将字符串解析为对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多