douhan1860 2016-10-13 01:00
浏览 80
已采纳

从PHP接收JSON到Angular 2 httpmodule

Using PHP I am echoing a response from SQL Server by using:

echo json_encode($total);

Just as a test, before I echo, I run error_log(json_encode($total)) which outputs the object as:

[{"address":"Mitchell Hwy",
  "description":"Nyngan Eastbound STC",
  "site_name":"T0242",
  "heading":"East",
  "vehicle_class":"B double",
  "vehicle_class_id":"10",
  "avg_speed":"69.27",
  "volume":"46"}]

Which is exactly what I want to receive within Angular 2's http response. My Angular 2 code is:

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http.post(url, sentArray,{
      headers: headers
    }).subscribe(
      result => returnedJSON = result,
      () => console.log("Failed..."),
      () => console.log(returnedJSON)
    );

This prints a 'Response' object in the console, where the Response 'body' is the returned PHP code that I want.

Response {_body: "[{"address":"Mitchell Hwy","description":"Nyngan E…_id":"Total","avg_speed":"67.35","volume":"262"}]", 
status: 200, 
ok: true, 
statusText: "OK", 
headers: Headers…}

My questions are: Why am I receiving an entire response object? Is this because I used POST HTTP request - or just the way the Angular 2 receives the response? How do I isolate just the Response body?

I assume I am doing everything correctly in PHP since I am logging the exact output that I want. I assume that this is something to do with my Angular 2 code...

  • 写回答

1条回答 默认 最新

  • dputlf5431 2016-10-13 01:07
    关注

    I apologise - In case anyone else got stuck at the same point, the answer is really simple. You isolate the response body using '.text()'. I found this here: https://angular.io/docs/ts/latest/api/http/index/Response-class.html

        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
    
        return this.http.post(url, sentArray,{
          headers: headers
        }).subscribe(
          result => returnedJSON = result.text(), //the '.text()' was the issue.
          () => console.log("Failed..."),
          () => console.log(returnedJSON)
        );
    

    EDIT

    Harry Ninh provided a better solution. Using 'result.json()' instead of '.text()'. 'Result.json()' returns an object array which was better for me.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?