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.

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

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历