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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料